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

相关推荐
用户805533698031 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
xcyxiner1 天前
DicomViewer (vcpkg Windows和ubuntu编译)7
qt
Quz6 天前
QML Hello World 入门示例
qt
xcyxiner9 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner10 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner10 天前
DicomViewer (添加模型类)3
qt
xcyxiner11 天前
DicomViewer (目录调整) 2
qt
xcyxiner11 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
LDR00613 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术13 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript