在特定时间更改QLabel的背景颜色

问题描述 投票:1回答:2

我的Qt代码中有一个定义背景颜色的QLabel。

我会在一个函数中只改变背景颜色一秒钟,然后将其设置回原始颜色。

我想过使用sleep()函数但有没有办法在不阻塞其他程序活动的情况下执行此操作?

谢谢!

c++ qt qt5 qlabel
2个回答
1
投票

你必须使用QTimer::singleShot(...)QPalette

#include <QApplication>
#include <QLabel>
#include <QTimer>

class Label: public QLabel{
public:
    using QLabel::QLabel;
    void changeBackgroundColor(const QColor & color){
        QPalette pal = palette();
        pal.setColor(QPalette::Window, color);
        setPalette(pal);
    }
    void changeBackgroundColorWithTimer(const QColor & color, int timeout=1000){
        QColor defaultColor = palette().color(QPalette::Window);
        changeBackgroundColor(color);
        QTimer::singleShot(timeout, [this, defaultColor](){
            changeBackgroundColor(defaultColor);
        });
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Label label;
    label.setText("Hello World");
    label.show();
    label.changeBackgroundColorWithTimer(Qt::green, 2000);
    return a.exec();
}

0
投票

也许你可以使用QTimer等一下。使用timer->start(1000)等待一秒钟,然后在你的班级中创建一个SLOT,重新获取Qtimer::timeOut信号以更改标签背景颜色。

© www.soinside.com 2019 - 2024. All rights reserved.