QT打开文件--对话窗口,名称和路径提取

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();

 

你可能感兴趣的:(QT)