• QT实验之闪烁灯


    QT实验之闪烁灯


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

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

    以下是一个简单的示例:

    #include   
    #include   
    #include   
    #include   
      
    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();  
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

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

  • 相关阅读:
    源码级别+操作系统级别解密RocketMQ 存储原理
    我寻找的方向
    【兔子王赠书第3期】《案例学Python(进阶篇)》
    基于SSM的家政服务网站
    JVM系列:JDK、JRE、JVM 的关系
    数据库设计三大范式
    Linux基础
    Elasticsearch:使用反向地理编码在地图上显示自定义区域统计数据
    springboot社区再生资源上门回收平台毕业设计-附源码072049
    模拟实现string【C++】
  • 原文地址:https://blog.csdn.net/techenliu/article/details/133388947