3

I have in my Qt code a QLabel with a defined background color.

I would in a function to change the background color for one second only and then set it back to the original color.

I thought about using a sleep() function but is there a way to do that without blocking the rest of the program activities ?

Thanks!

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
E.F
  • 199
  • 1
  • 1
  • 10

2 Answers2

3

You have to use a QTimer::singleShot(...) and 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();
}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
0

Maybe you can use QTimer to wait a second. Use timer->start(1000) to wait a second and create a SLOT in your class that recive the Qtimer::timeOut signal to changeback the label background color.

Zharios
  • 183
  • 1
  • 18