QFileDialog
我们经常使用QFileDialog中的打开文件对话框、保存文件对话框,Qt中我们一般使用此类中的静态成员函数,非常方便,举例如下:
bool MainWindow::openSourceFileSlot()
{
QString tempPath = QFileDialog::getOpenFileName(this, QStringLiteral("打开"), fileDialogPath, QStringLiteral("video (*.avi;*.mp4;*.asf);;All (*.*)"));
if(!tempPath.isEmpty())
{
this->openSourceFileName = tempPath;
stack1OpenUi->openSourceLineEdit->setText(tempPath);
fileDialogPath = QFileInfo(tempPath).path();
qCInfo(QLoggingCategory("custom")) << QString("Open file's name is %1").arg(tempPath);
return true;
}
else
{
qCInfo(QLoggingCategory("custom")) << QString("Give up open file, old filePath is %1").arg(openSourceFileName);
return false;
}
}
bool MainWindow::saveSourceFileSlot()
{
QString tempPath = QFileDialog::getSaveFileName(this, QStringLiteral("保存"), fileDialogPath, tr("Jpg(*.jpg);;All (*.*)"));
if(!tempPath.isEmpty())
{
stack1SaveUi->saveSourceLineEdit->setText(tempPath);
saveSourceFileName = tempPath;
fileDialogPath = QFileInfo(tempPath).path();
qCInfo(QLoggingCategory("custom")) << QString("Save source file's name is %1").arg(tempPath);
return true;
}
else
{
qCInfo(QLoggingCategory("custom")) << QString("Give up open file, old save source file's name is %1").arg(tempPath);
return false;
}
}
上例中,getSaveFileName()函数的第三个参数是程序启动时在构造函数中通过QSetting类获取的,在程序关闭时通过在析构函数中调用QSetting类将fileDialogPath保存到系统注册表中,这样可以实现程序每次打开此类打开文件或保存文件对话框时都会从上次打开的路径处进行打开。
实现此功能还需要获取getSaveFileName()或getOpenFileName()函数返回的文件名称(绝对路径的形式)所在目录的路径,即我们要获取所打开或保存文件所在文件夹的绝对路径,并保存在变量fileDialogPath中,如上例,我们可以使用QFileInfo类进行获取,也非常方便,其实还有另外一种方式,实例化QFileDialog调用其成员函数QFileDialog::directory()获取路径:
bool MainWindow::saveSourceFileSlot()
{
QFileDialog fileDialog;
fileDialog.setWindowTitle(QStringLiteral("保存"));
fileDialog.setDirectory(fileDialogPath);
fileDialog.setNameFilter(tr("Jpg(*.jpg);;All (*.*)"));
if(!fileDialog.exec())
{
qCInfo(QLoggingCategory("custom")) << QString("Give up open file, old save source file's name is %1").arg(tempPath);
return false;
}
QString tempPath = fileDialog.selectedFiles().at(0);
stack1SaveUi->saveSourceLineEdit->setText(tempPath);
saveSourceFileName = tempPath;
fileDialogPath = fileDialog.directory().absolutePath();
qCInfo(QLoggingCategory("custom")) << QString("Save source file's name is %1").arg(tempPath);
return true;
}
但这种方式略显笨拙。
上例中qCInfo用来输出到日志文件,可以忽略。