Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to show a text for 3 sec?



  • I want to show a qlabel for 3 sec and used the following code. The label is initially hidden.

    ui->qlabel->show();
    QThread::sleep(3);
    ui->qlabel->hide();
    

    But the label didn't show up at all. I tried to comment ui->qlabel->hide(); and the label appeared after 3 sec waiting. What's wrong with these steps?



  • Hi,
    By using QThread::sleep(), you are blocking the event loop, which can cause the effect you are describing.

    Do that instead:

    ui->qlabel->show();
    QTimer::singleShot(3000, ui->qlabel, &QWidget::hide);
    

    You should avoid as much as possible usage of QThread::sleep(), QThread::msleep() or QThread::usleep() from the GUI (main) thread, try to use signal & slots or QTimer to make this kind of behavior to keep you application responsive and avoid "freezing" of the window.



  • @Gojir4 said in How to show a text for 3 sec?:

    Hi,
    By using QThread::sleep(), you are blocking the event loop, which can cause the effect you are describing.

    Do that instead:

    ui->qlabel->show();
    QTimer::singleShot(3000, ui->qlabel, &QWidget::hide);
    

    You should avoid as much as possible usage of QThread::sleep(), QThread::msleep() or QThread::usleep() from the GUI (main) thread, try to use signal & slots or QTimer to make this kind of behavior to keep you application responsive and avoid "freezing" of the window.

    This worked perfectly. Thanks so much!

    I have another question. Is it possible to set a fade effect when the label is hiding or showing?


  • Qt Champions 2019



  • I think this should do the job (not tested and compiled):

    //mywidget.h
    QPropertyAnimation *m_animation;
    
    //mywidget.cpp
    //Constructor
    void MyWidget::MyWidget(QWidget *parent) 
        : QWidget(parent), ui(new Ui::MyWidget)
    {
        //...    
        m_animation = new QPropertyAnimation(ui->qlabel, "windowOpacity", this);    
        //See QPropertyAnimation documentation for more parameters
        m_animation->setDuration(1000);    
        m_animation->setStartValue(0.0);
        m_animation->setEndValue(1.0);
        //...
    }
    
    void MyWidget::showLabel(int duration)
    {   
        ui->qlabel->setWindowOpacity(0.0);
        ui->qlabel->show();
        m_animation->setDirection(QPropertyAnimation::Forward);
        m_animation->start();    
        //Ensure it's visible with 100% opacity at least 1 sec. 
        QTimer::singleShot(qMax(2000, duration), this, &MyWidget::hideLabel);
    }
    
    void MyWidget::hideLabel()
    {
        m_animation->setDirection(QPropertyAnimation::Backward);
        m_animation->start();
        QTimer::singleShot(m_animation.duration(), ui->qlabel, &QWidget::hide);
    }
    

Log in to reply