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

相关推荐
Wenweno0o18 小时前
0基础Go语言Eino框架智能体实战-chatModel
开发语言·后端·golang
chenjingming66619 小时前
jmeter线程组设置以及串行和并行设置
java·开发语言·jmeter
cch891819 小时前
Python主流框架全解析
开发语言·python
不爱吃炸鸡柳19 小时前
C++ STL list 超详细解析:从接口使用到模拟实现
开发语言·c++·list
十五年专注C++开发19 小时前
RTTR: 一款MIT 协议开源的 C++ 运行时反射库
开发语言·c++·反射
Momentary_SixthSense19 小时前
设计模式之工厂模式
java·开发语言·设计模式
‎ദ്ദിᵔ.˛.ᵔ₎19 小时前
STL 栈 队列
开发语言·c++
勿忘,瞬间19 小时前
数据结构—顺序表
java·开发语言
张張40819 小时前
(域格)环境搭建和编译
c语言·开发语言·python·ai
weixin_4235339919 小时前
【Windows11离线安装anaconda、python、vscode】
开发语言·vscode·python