在Qt中用CommandLinkButton控件实现图片浏览器的功能。
主要控件说明:
控件类型 控件名称 控件说明 文本 QLabel imageLabel 显示图片 TextLabel QCommandLinkButton commandLinkButtonNext 触发下一张图片 下一张
- 建立Qt Gui Application工程,可翻看前面博文,在此不再赘述。
- 添加资源文件:在工程目录下新建文件夹images,文件夹中有5张照片,分别是1.jpg、2.jpg、3.jpg、4.jpg、5.jpg。
- 我的工程目录是:/home/new/Desktop/qtstudy/button/CommandLinkButton
- 在工程名称上右击,选择“Add New”,选择“Qt”下的“Qt Resource file”。选择“Choose”确定。
5.在“Name”后面添加“images”,“Path”后的路径为images路径,我的为:/home/new/Desktop/qtstudy/button/CommandLinkButton
6.点击“Next”,将选项配置如下图,Add to project下选择<None>,单击“Finish”
7.单击“Add”,选择“Add Prefix”,即添加前缀。然后再Add Prefix选项下添加“/”,如下图:
8.单击“Add”,选择“Add Files”,选中“images”目录下的所有图片文件,单击“打开”,添加成功后如下图:
9.点击工程目录下的.ui文件,拖拽一个QLable控件和QCommandLinkButton控件,布局如下:
10.在.h文件中添加如下代码:Ui::MainWindow *ui;后面是添加的代码
private: Ui::MainWindow *ui; QStringList list; //用于保存文件名称 int currentImage; //用于循环图片 private slots: void on_commandLinkButtonNext_clicked(); //槽函数,点击后显示下一张图片
11.在.cpp文件下添加头文件和源代码:除去原来工程自带的,还需添加部分代码,其他文件不需添加代码。请读者自己对照完善。一定要注意照片的路径。
最后的函数是槽函数的定义。#include "mainwindow.h" #include "ui_mainwindow.h" #include <QMessageBox> #include <QFileDialog> #include <QImage> #include <QString> #include <QPalette> #include <QSizePolicy> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); this->currentImage = 0; //初始化文件列表,注意照片路径,我的是/home/new/Desktop/qtstudy/button/CommandLinkButton/ this->list<<"/home/new/Desktop/qtstudy/button/CommandLinkButton/images/1.jpg" <<"/home/new/Desktop/qtstudy/button/CommandLinkButton/images/2.jpg" <<"/home/new/Desktop/qtstudy/button/CommandLinkButton/images/3.jpg" <<"/home/new/Desktop/qtstudy/button/CommandLinkButton/images/4.jpg" <<"/home/new/Desktop/qtstudy/button/CommandLinkButton/images/5.jpg"; //设置imageLabel的大小和背景 ui->imageLabel->setBackgroundRole(QPalette::Base); ui->imageLabel->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Ignored); ui->imageLabel->setScaledContents(true); // resize(400,400); QString fileName = list.at(this->currentImage); if(!fileName.isEmpty()) { QImage image(fileName); if(image.isNull()) { QMessageBox::information(this,tr("Image Viewer"),tr("Cannot load %1.").arg(fileName)); return ; } ui->imageLabel->setPixmap(QPixmap::fromImage(image)); } } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_commandLinkButtonNext_clicked() { if(this->currentImage == 4) this->currentImage = 0; else this->currentImage++; QString fileName = list.at(this->currentImage); if(!fileName.isEmpty()) { QImage image(fileName); if(image.isNull()) { QMessageBox::information(this,tr("Image Viewer"),tr("Cannot load %1.").arg(fileName)); return ; } ui->imageLabel->setPixmap(QPixmap::fromImage(image)); } }
12.编译运行,最后结果如下图: