QT開啟檔案--對話視窗,名稱和路徑提取
阿新 • • 發佈:2018-11-12
QT一般要用到檔案選操作,以開啟圖片為例,以下為部分程式碼:
QImage openImage() { QString filename = QFileDialog::getOpenFileName(this, tr("choose a pic"), "", tr("Images (*.png *.bmp *.jpg *.tif *.GIF *.jpeg)")); if (filename.isEmpty()) { return; } QImage image= QImage(filename); return image; //可用opencv作為轉換 Mat imageread; imageread = imread(filename.toLatin1().data(), 1); return Mat2QImage(imageread); } QImage Mat2QImage(const cv::Mat& mat) { // 8-bits unsigned, NO. OF CHANNELS = 1 if (mat.type() == CV_8UC1) { QImage image(mat.cols, mat.rows, QImage::Format_Indexed8); image.setColorCount(256); for (int i = 0; i < 256; i++) { image.setColor(i, qRgb(i, i, i)); } // Copy input Mat uchar *pSrc = mat.data; for (int row = 0; row < mat.rows; row++) { uchar *pDest = image.scanLine(row); memcpy(pDest, pSrc, mat.cols); pSrc += mat.step; } return image; } // 8-bits unsigned, NO. OF CHANNELS = 3 else if (mat.type() == CV_8UC3) { // Copy input Mat const uchar *pSrc = (const uchar*)mat.data; // Create QImage with same dimensions as input Mat QImage image(pSrc, mat.cols, mat.rows, mat.step, QImage::Format_RGB888); return image.rgbSwapped(); } else if (mat.type() == CV_8UC4) { qDebug() << "CV_8UC4"; // Copy input Mat const uchar *pSrc = (const uchar*)mat.data; // Create QImage with same dimensions as input Mat QImage image(pSrc, mat.cols, mat.rows, mat.step, QImage::Format_ARGB32); return image.copy(); } else { qDebug() << "ERROR: Mat could not be converted to QImage."; return QImage(); } }
對於分析檔名稱和路徑可以用已封裝好的函式。
QString file_full, file_name, file_path;
QFileInfo fi;
file_full = QFileDialog::getOpenFileName(this);
fi = QFileInfo(file_full);
file_name = fi.fileName();
file_path = fi.absolutePath();