实现这个功能,需要以下步骤:
在Qt设计师中创建一个QLabel组件,并将其大小设置为与图片大小相同。加载一张图片到该QLabel组件中。
编写槽函数,当按钮被点击时触发该函数。在该函数中使用QPainter对象绘制一个矩形框(即正方形)。
使用QTimer定时器,在每次时间间隔到达时,切换绘制的矩形框的颜色来实现闪烁效果。
下面是完整的代码:
mainwindow.h文件:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QImage>
#include <QPainter>
#include <QTimer>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_pushButton_clicked();
void updateColor();
private:
Ui::MainWindow *ui;
QImage m_image;
QTimer* m_timer;
QColor m_color;
};
#endif // MAINWINDOW_H
mainwindow.cpp文件:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
m_color(Qt::red)
{
ui->setupUi(this);
m_image.load(":/image/image.png");
ui->label->setPixmap(QPixmap::fromImage(m_image));
m_timer = new QTimer(this);
connect(m_timer, SIGNAL(timeout()), this, SLOT(updateColor()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
QPainter painter(&m_image);
painter.setPen(QPen(m_color, 5));
painter.drawRect(50, 50, 100, 100);
ui->label->setPixmap(QPixmap::fromImage(m_image));
m_timer->start(500);
}
void MainWindow::updateColor()
{
if (m_color == Qt::red)
m_color = Qt::green;
else
m_color = Qt::red;
QPainter painter(&m_image);
painter.setPen(QPen(m_color, 5));
painter.drawRect(50, 50, 100, 100);
ui->label->setPixmap(QPixmap::fromImage(m_image));
}
在这个代码中,我们使用了QImage来加载图片,并将其显示在QLabel组件中。当按钮被点击时,我们使用QPainter对象在图片上绘制一个矩形框。然后使用QTimer定时器,在每次时间间隔到达时,切换绘制的矩形框的颜色来实现闪烁效果。最后,使用QImage的setPixmap函数将更新后的图片显示在QLabel组件中。