QT实验之闪烁灯

QT实验之闪烁灯

在QT中,使用QPainter来实现闪烁灯效果的一种方法是使用QTimer来周期性地改变灯的状态。

首先,你需要一个QPixmap对象,它包含了灯的图片。然后,使用QTimer来周期性地切换灯的状态。当灯的状态改变时,你需要重新绘制QPixmap。

以下是一个简单的示例:

cpp 复制代码
#include <QApplication>  
#include <QPainter>  
#include <QLabel>  
#include <QTimer>  
  
class FlashingLight : public QLabel {  
public:  
    FlashingLight(QWidget *parent = nullptr)  
        : QLabel(parent)  
    {  
        // 设置初始灯的状态为关闭  
        isOn = false;  
  
        // 创建一个定时器来改变灯的状态  
        QTimer *timer = new QTimer(this);  
        connect(timer, &QTimer::timeout, this, &FlashingLight::toggleLight);  
        timer->start(500);  // 每500毫秒切换一次状态  
    }  
  
protected:  
    void paintEvent(QPaintEvent *) override {  
        QPainter painter(this);  
        QPixmap pixmap(":/images/light.png");  // 加载灯的图片  
        painter.drawPixmap(0, 0, pixmap.scaled(size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));  
    }  
  
private slots:  
    void toggleLight() {  
        isOn = !isOn;  // 切换灯的状态  
        update();  // 重新绘制灯  
    }  
  
private:  
    bool isOn;  // 灯的状态,true表示打开,false表示关闭  
};  
  
int main(int argc, char **argv) {  
    QApplication app(argc, argv);  
    FlashingLight light;  
    light.show();  
    return app.exec();  
}

在这个示例中,FlashingLight是一个继承自QLabel的类。在paintEvent()函数中,我们使用QPainter来绘制一个QPixmap对象。这个QPixmap对象包含了灯的图片。我们使用QTimer来周期性地切换灯的状态。当灯的状态改变时,我们调用update()函数来重新绘制灯。

相关推荐
CSDN_RTKLIB1 天前
【One Definition Rule】类重复定义解决思路
开发语言·c++
落羽凉笙1 天前
【Python基础】第2章学习笔记:从Python历史到IPO编程模式,含习题详解
开发语言·笔记·后端·python·学习
刘97531 天前
【第24】天24c#今日小结
开发语言·c#
星空露珠1 天前
时间罗盘小界面模组
开发语言·数据结构·算法·游戏·lua
DeniuHe1 天前
C++实现在数组中找到重复元素及其出现的次数。
开发语言·c++·哈希算法
Byron Loong1 天前
【Python】Pytorch是个什么包
开发语言·pytorch·python
qq_5470261791 天前
多版本 JDK 安装与配置
java·开发语言
shbelec1 天前
实邦电子如何确保电子产品开发质量与可靠性?
开发语言
we have a whole life1 天前
Golang(Handler入门)
开发语言·http·golang