Qt实战案例(51)——利用Qt实现打开最近图片功能

Qt实战案例(51)——利用Qt实现打开最近图片功能,第1张

目录
    • 一、项目介绍
    • 二、项目基本配置
    • 三、UI界面设置
    • 四、主程序实现
      • 4.1 mainwindow.h头文件
      • 4.2 mainwindow.cpp源文件
    • 五、效果演示

一、项目介绍

本文介绍利用Qt和QSettings实现打开最近图片功能。

二、项目基本配置

新建一个Qt案例,项目名称为“RecentPhotoTest”,基类选择“QMainWindow”,取消选中创建UI界面复选框,完成项目创建。

三、UI界面设置

无UI界面

四、主程序实现 4.1 mainwindow.h头文件

头文件中需要声明若干槽函数、变量和相应函数:

private:
    QMenu* fileMenu;
    QMenu* recentFilesMenu;

    QAction* openAction;
    QList<QAction*> recentFileActionList;
    const int maxFileNr=5;

    QString currentFilePath;
    QLabel *imageLabel;

    void loadFile(const QString& filePath);
    void adjustForCurrentFile(const QString& filePath);
    void updateRecentActionList();
4.2 mainwindow.cpp源文件

需要在构造函数中添加如下代码:

    imageLabel = new QLabel;
    setCentralWidget(imageLabel);//设置中心部件
    //Open Action
    openAction = new QAction(tr("&Open..."), this);//open
    openAction->setShortcuts(QKeySequence::Open);  //设置快捷键
    connect(openAction, &QAction::triggered, this, [=]()
    {
        QString filePath = QFileDialog::getOpenFileName(
                           this, tr("Open File"), "",
                           tr("Images (*.png *.xpm *.jpg *.gif)"));
        if (!filePath.isEmpty())
            loadFile(filePath);
    });

    //recentFile Action
    QAction* recentFileAction = nullptr;
    for(auto i = 0; i < maxFileNr; ++i){
        recentFileAction = new QAction(this);
        recentFileAction->setVisible(false);

        connect(recentFileAction, &QAction::triggered, this, [=]()
        {
            loadFile(recentFileAction->data().toString());
        });
        recentFileActionList.append(recentFileAction);
    }

    // create menus
    fileMenu = menuBar()->addMenu(tr("&File"));
    fileMenu->addAction(openAction);

    recentFilesMenu = fileMenu->addMenu(tr("Open Recent"));
    for(auto i = 0; i < maxFileNr; ++i)
        recentFilesMenu->addAction(recentFileActionList.at(i));

    updateRecentActionList();

    resize(350, 250);//调整尺寸

新建一个imageLabel,用于图片显示;新建Open Action和RecentFile Action,将这两个action与相应的槽函数相连,然后在菜单栏上创建File和Open Recent菜单,用于承接相应的action,最后更新RecentActionList及调整尺寸。

当点击Open菜单时,选择图像并在界面中进行显示:

//加载图片
void MainWindow::loadFile(const QString &filePath){
    QFile file(filePath);
    //如果不能打开
    if (!file.open(QFile::ReadOnly)) {
        QMessageBox::warning(this, tr("Recent Photos"),
                             tr("This file could not be found:\n%1.")
                             .arg(filePath));
        return;
    }

    QPixmap pMap(filePath);
    //如果图片为空
    if (pMap.isNull()) {
        QMessageBox::information(this, tr("Recent Photos"),
                      tr("Cannot load:\n%1.")
                      .arg(filePath));
        return;
    }

    imageLabel->setPixmap(pMap);                //显示图像
    imageLabel->setAlignment(Qt::AlignCenter);  //居中对齐
    adjustForCurrentFile(filePath);
}

调整菜单中最近文件的位置,使得每次新打开的文件都在RecentFile Action菜单栏的最上方:

//调整当前文件(使得每次新打开的文件都在最上方)
void MainWindow::adjustForCurrentFile(const QString &filePath){
    currentFilePath = filePath;
    setWindowFilePath(currentFilePath);


    QSettings settings("Recently", "Recent Photos");
    QStringList recentFilePaths = settings.value("recentPhotos").toStringList();//获取键对应的值
    recentFilePaths.removeAll(filePath);    //移除filePath
    recentFilePaths.prepend(filePath);      //在开头增加filePath
    //如果尺寸超过最大尺寸,则删除最后一项
    while (recentFilePaths.size() > maxFileNr)
        recentFilePaths.removeLast();
    settings.setValue("recentPhotos", recentFilePaths);//设置键recentPhotos对应的值

    updateRecentActionList();
}

最后更新RecentActionList,使得每次打开的图片都放到RecentActionList中:

//更新recentFileActionList
void MainWindow::updateRecentActionList(){
    QSettings settings("Recently", "Recent Photos");
    QStringList recentFilePaths = settings.value("recentPhotos").toStringList();//获取键对应的值

    auto itEnd = 0;
    if(recentFilePaths.size() <= maxFileNr)
        itEnd = recentFilePaths.size();
    else
        itEnd = maxFileNr;

    for (auto i = 0; i < itEnd; ++i) {
        QString strippedName = QFileInfo(recentFilePaths.at(i)).fileName();//返回文件名(不包含路径)
        recentFileActionList.at(i)->setText(strippedName);  //描述性文本
        recentFileActionList.at(i)->setData(recentFilePaths.at(i)); //数据
        recentFileActionList.at(i)->setVisible(true);
    }

    for (auto i = itEnd; i < maxFileNr; ++i)
        recentFileActionList.at(i)->setVisible(false);
}
五、效果演示

完整效果如下:

如果没有看懂的话,完整代码可以参考:https://download.csdn.net/download/didi_ya/85631611


ok,以上便是本文的全部内容了,如果对你有所帮助,记得点个赞哟~

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1499153.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-25
下一篇 2022-06-25

发表评论

登录后才能评论

评论列表(0条)

保存