【发布时间】:2019-02-05 01:12:36
【问题描述】:
我的 Qt 代码中有一个带有已定义背景颜色的 QLabel。
我会在一个函数中只更改背景颜色一秒钟,然后将其设置回原始颜色。
我考虑过使用 sleep() 函数,但有没有办法在不阻塞其余程序活动的情况下做到这一点?
谢谢!
【问题讨论】:
-
QTimer 可能有用。
我的 Qt 代码中有一个带有已定义背景颜色的 QLabel。
我会在一个函数中只更改背景颜色一秒钟,然后将其设置回原始颜色。
我考虑过使用 sleep() 函数,但有没有办法在不阻塞其余程序活动的情况下做到这一点?
谢谢!
【问题讨论】:
您必须使用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();
}
【讨论】:
也许您可以使用QTimer 稍等片刻。使用timer->start(1000) 稍等片刻,然后在您的类中创建一个接收Qtimer::timeOut 信号以更改标签背景颜色的SLOT。
【讨论】: