QT开发中文网

C++点击按钮后让Qpainter在Qlabel图片中画出的正方形闪烁起来

实现这个功能,需要以下步骤:

  1. 在Qt设计师中创建一个QLabel组件,并将其大小设置为与图片大小相同。加载一张图片到该QLabel组件中。

  2. 编写槽函数,当按钮被点击时触发该函数。在该函数中使用QPainter对象绘制一个矩形框(即正方形)。

  3. 使用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组件中。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=684

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?