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()函数来重新绘制灯。

相关推荐
破茧蝴蝶5 小时前
Python分布式爬虫完整教程
开发语言·python
狗凯之家源码网5 小时前
全新 PHP 轻量客服聊天室源码深度评测
开发语言·php·聊天室系统
远离UE45 小时前
UE5 Substrate Thin Film 源码拆析
开发语言·javascript·ue5
keyipatience5 小时前
JavaScript学习(1)书写位置,变量、数据类型、运算符
开发语言·前端·javascript·css·学习
栈帧之外6 小时前
【C++】STL之set
开发语言·c++
catchadmin7 小时前
免费可商用 PHP 管理后台 CatchAdmin V5.4.1 发布,新增 MCP 支持
开发语言·php
jimy18 小时前
c++的 Type Traits (二、更详细版本)
开发语言·c++
狗凯之家源码网9 小时前
纯 PHP+MySQL 应用市场系统源码实测!
开发语言·mysql·php
dishugj9 小时前
系统架构风险点、敏感点和权衡点的概念和区分
java·开发语言
geovindu9 小时前
rust:Memento Pattern(续)
开发语言·后端·设计模式·rust·行为模式·备忘录模