要求:
点击上一张或者下一张实现图片的切换显示
1、项目架构
2、UI界面的设计
3、添加图片到项目静态资源
4、主要代码的实现
showimgDialog.h 文件
#ifndef SHOWIMGDIALOG_H
#define SHOWIMGDIALOG_H
#include <QDialog>
#include <QPainter> // 画家类
#include <QImage> // 图片
QT_BEGIN_NAMESPACE
namespace Ui { class ShowimgDialog; }
QT_END_NAMESPACE
class ShowimgDialog : public QDialog
{
Q_OBJECT
public:
ShowimgDialog(QWidget *parent = nullptr);
~ShowimgDialog();
private slots:
// 上一张对应的槽函数
void on_m_btnPrev_clicked();
// 下一张对应的槽函数
void on_m_btnNext_clicked();
private:
// 绘图事件处理函数(虚函数)
void paintEvent(QPaintEvent *) ;
private:
Ui::ShowimgDialog *ui;
int m_index; // 图片的 索引
};
#endif // SHOWIMGDIALOG_H
showimgDialog.cpp 文件
#include "showimgdialog.h"
#include "ui_showimgdialog.h"
ShowimgDialog::ShowimgDialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::ShowimgDialog)
{
ui->setupUi(this);
m_index = 0 ;
}
ShowimgDialog::~ShowimgDialog()
{
delete ui;
}
// 上一张对应的槽函数
void ShowimgDialog::on_m_btnPrev_clicked()
{
if(--m_index < 0)
{
m_index = 9 ;
}
update(); // 除法绘图事件执行
}
// 下一张对应的槽函数
void ShowimgDialog::on_m_btnNext_clicked()
{
if(++m_index > 9)
{
m_index = 0 ;
}
update(); // 除法绘图事件执行
}
// 绘图事件处理函数(虚函数)
void ShowimgDialog::paintEvent(QPaintEvent *)
{
// qDebug("paintEvent") ;
// 1. 创建画家对象
QPainter painter(this);
// 2. 获取绘图所在矩形区域
QRect rect = ui->frame->frameRect();
// 坐标值平移,使rect 和 printer使用相同的坐标系
rect.translate(ui->frame->pos()) ;
// 3.构建要绘制的图形对象
QImage image(":/n/images/"+QString::number(m_index)+".jpg");
// 4. 使用painter将image图片画到rect上
painter.drawImage(rect, image);
}
main.cpp 文件
#include "showimgdialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ShowimgDialog w;
w.show();
return a.exec();
}
5、运行效果
未完待续
有疑问的小伙伴可以留言一起交流讨论!!!