您的位置:首页 > 编程语言 > Qt开发

如何在Qt中添加资源文件

2013-12-19 11:31 351 查看
在Qt中用CommandLinkButton控件实现图片浏览器的功能。

主要控件说明:

控件类型控件名称控件说明文本
QLabelimageLabel显示图片TextLabel
QCommandLinkButtoncommandLinkButtonNext触发下一张图片下一张
建立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.编译运行,最后结果如下图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息