我的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)
等待一秒钟,然后在你的班级中创建一个SLOT,重新获取Qtimer::timeOut
信号以更改标签背景颜色。