QFileDialog的使用

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用来输出到日志文件,可以忽略。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值