How to use QTimer in right way ?



  • Hi,
    I'm new with Qt and use QTimer but It does not work as my expecting. My issue is:
    I have a button. When the button is activated, It will show a QWidget and start countdown timer 8 second to hide the QWidget. However, I want restart countdown timer to 8 second if the button is activated again and countdown timer is less than 8 second.
    This is my code:

    void trigger(QString message){
                  unsigned int timeout = 8000;
                  ui->l_Info->setText(message);
                  ui->l_Info->move(0, 0);
                  ui->l_Info->show();
                  QTimer::singleShot(timeout, this, SLOT(hideMessageAtn()));
    }
    
    void hideMessageAtn(){
                  ui->l_Info->hide();
    }
    

    Actually, this code does work as my expecting. If I activate button in countdown time, it does not reset coundown timer and still emit hideMessageAtn() in the timeout.
    So anyone give me in this case ?
    Thank in advance.



  • @Hung-Tran ,

    Once the pushbutton is clicked, show the widget, if the timer is already active, stop it, set the interval to 8 seconds and then start the timer. Once after the timeout, hide the widget.



  • Hi,
    AFAIK, there is no easy way to reset a QTimer the way you declared it. Your best bet is to create an object of type QTimer, like this

    QTimer *timer = new QTimer(this);
    

    And in your "trigger" function you should do something like this:

    timer->setSingleShot(true);
    timer->start(timeout); //If timer was running, it will restart
    


  • @Hung-Tran ,

    myWidget::myWidget()
    {
    timer = new QTimer(this);
    m_Button = new QPushButton("Click");
    widget = new QWidget;
    timer->setSingleShot(true);
    connect(m_Button,SIGNAL(clicked()), this,SLOT(on_pushButton_clicked()));
    connect(timer,SIGNAL(timeout()), this,SLOT(on_TimerTick()));
    }
    void myWidget::on_TimerTick()
    {
    widget ->hide();
    }
    void myWidget::on_pushButton_clicked()
    {
    widget ->show();
    timer->stop();
    timer->setInterval(8000);
    timer->start();
    }



  • @Vinod-Kuntoji said in How to use QTimer in right way ?:

    ...
    void myWidget::on_pushButton_clicked()
    {
    ...
    timer->stop();
    timer->setInterval(8000);
    timer->start();
    }

    This code is a bit reduntant. simply calling timer->start(8000) will pretty much do the same;

    Here is a quote from Docs (link):

    Starts or restarts the timer with the timeout specified in interval.
    If the timer is already running, it will be stopped and restarted.
    If singleShot is true, the timer will be activated only once.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.