【问题标题】:Change background color of a QLabel for a specific time在特定时间更改 QLabel 的背景颜色
【发布时间】:2019-02-05 01:12:36
【问题描述】:

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

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

我考虑过使用 sleep() 函数,但有没有办法在不阻塞其余程序活动的情况下做到这一点?

谢谢!

【问题讨论】:

  • QTimer 可能有用。

标签: c++ qt qt5 qlabel


【解决方案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();
}

【讨论】:

    【解决方案2】:

    也许您可以使用QTimer 稍等片刻。使用timer-&gt;start(1000) 稍等片刻,然后在您的类中创建一个接收Qtimer::timeOut 信号以更改标签背景颜色的SLOT。

    【讨论】:

    • 举个例子可能也会有帮助。
    猜你喜欢
    • 2017-06-13
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多