Qt实战案例(52)——利用Qt实现打开最近图片功能(利用QPushButton按钮实现)

上文【Qt实战案例(51)——利用Qt实现打开最近图片功能】和上上文【Qt实战案例(50)——利用Qt实现打开最近文档功能】分别介绍了利用菜单栏action实现打开最近图片功能和打开最近文档功能,并在菜单栏显示最近图片和最近文档名称。本文将介绍利用按钮QPushButton实现打开最近图片功能并在按钮上显示图片名称。

一、项目介绍

本文介绍利用QPushButton按钮和QButtonGroup按钮组实现打开最近图片功能。(存储在QSettings中)

二、项目基本配置

新建一个Qt案例,项目名称为“PhotoTest”,基类选择“QWidget”,点击选中创建UI界面复选框,完成项目创建。

三、UI界面设置

UI界面如下:
在这里插入图片描述
UI界面控件布局如下:

序号 名称 类型 属性
pbn_choose QPushButton text:选择
pbn1 QPushButton text:
pbn2 QPushButton text:
pbn3 QPushButton text:
label_recent QLabel text:最近
label QLabel /

四、主程序实现

4.1 widget.h头文件

头文件中声明两个槽函数和若干个私有变量和函数:

private slots:
    void on_pbn_choose_clicked();
    void slot_CheckBoxGroupClicked(int id);

private:
    QButtonGroup *group;
    const int maxFileNr=3;//最大显示三个最近
    QList<QString> recentList;
    QString currentFilePath;

    void loadFile(const QString &filePath);
    void updateRecentList();
    void adjustForCurrentFile(const QString &filePath);

4.2 widget.cpp源文件

需要在构造函数中首先定义一个QButtonGroup按钮组,包含三个按钮:pbn1、pbn2和pbn3并设置相应的id,然后设置按钮默认不可见,设置按钮可选(By default, the button is not checkable.)之后将按钮组连接信号与槽,保证能够识别哪个按钮被按下,最后更新RecentList,代码如下:

    //按钮组
    group = new  QButtonGroup(this);
    group->setObjectName("group");
    group->addButton(ui->pbn1,0);
    group->addButton(ui->pbn2,1);
    group->addButton(ui->pbn3,2);
    //不可见
    group->button(0)->setVisible(false);
    group->button(1)->setVisible(false);
    group->button(2)->setVisible(false);
    //按钮可选
    group->button(0)->setCheckable(true);
    group->button(1)->setCheckable(true);
    group->button(2)->setCheckable(true);
    
    // 连接信号和槽
     connect(group, SIGNAL(idClicked(int)), this, SLOT(slot_CheckBoxGroupClicked(int)));


    updateRecentList();

on_pbn_choose_clicked槽函数用于响应用户点击“选择”按钮的操作:

//选择图片并加载
void Widget::on_pbn_choose_clicked()
{
    
    
    QString filePath = QFileDialog::getOpenFileName(
                this, tr("Choose Photo"), "",
                tr("Images (*.png *.xpm *.jpg *.gif)"));
    if (!filePath.isEmpty())
        loadFile(filePath);
}

loadFile函数将图片进行加载并在label中显示并居中对齐:

//加载图片
void Widget::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;
    }

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

按钮组对应的槽函数定义如下:

void Widget::slot_CheckBoxGroupClicked(int id)
{
    
    
    if( group->button(id)->isChecked())
    {
    
    
          loadFile(group->button(id)->accessibleDescription());
    }
}

该函数用于获取点击的按钮组的按钮的id并将该按钮的描述性文本accessibleDescription进行读取并显示在label中。

adjustForCurrentFile函数用于调整当前文件,使得每次新打开的文件都在最上方,代码如下:

//调整当前文件(使得每次新打开的文件都在最上方)
void Widget::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对应的值

    updateRecentList();
}

updateRecentList函数用于更新group->button,该函数首先获取recentFilePaths路径并获取其尺寸,然后逐个遍历获取其文件名strippedName(不包含路径),并将按钮组中button(i)的按钮名称设置为strippedName,将按钮组中button(i)的描述性信息设置为recentFilePaths(AccessibleDescription存放完整路径),并将其设置为可见,将其他按钮设置为不可见,代码如下:

//更新group
void Widget::updateRecentList(){
    
    
    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();//返回文件名(不包含路径)
        group->button(i)->setText(strippedName);  //设置按钮名称

        group->button(i)->setAccessibleDescription(recentFilePaths.at(i));
        //group->button(i)->setData(recentFilePaths.at(i)); //数据
        //qDebug()<<"recentFilePaths:"<<i<<recentFilePaths.at(i);

        group->button(i)->setVisible(true);
    }

    for (auto i = itEnd; i < maxFileNr; ++i)
        group->button(i)->setVisible(false);
}

五、效果演示

完整效果如下:
在这里插入图片描述

【注】:如果“最近”下面按钮已满,想清空,可直接对两个QSettings修改即可
在这里插入图片描述

如果没有看懂的话,完整代码可以参考:https://download.csdn.net/download/didi_ya/85639455
【注】:【注意:本程序仅适用于Qt5.15和Qt6以后版本】,如果Qt5.15以前版本需要,需自行修改代码第30行信号:idClicked(int)
在这里插入图片描述


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

猜你喜欢

转载自blog.csdn.net/didi_ya/article/details/125277852