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

How to implement a time delay



  • Hi,

    I've real-time signal, I need to check if the signal crosses a threshold and set a delay for about 1 second. How do I implement that?

    if(a_vertical> onThreshold) //what's the expression to set a time delay?
        {
            ui->rdo_btn_vertical->setStyleSheet(StyleSheetOn1); // On  LED
        }
        else
        {
            ui->rdo_btn_vertical->setStyleSheet(StyleSheetOff1); // Off LED
        }
    


  • @SruDom hi, you can use QTimer



  • @LeLev Hi, could you show me an example to set delay using QTimer?



  • @SruDom there are examples in the page i linked



  • I did something like this, and it works
    start QTimer in single shot mode and check if it's running (should not be) while checking the threshold:

    if(a_vertical> onThreshold && !timer.isActive()) 
        {
            emit startTimer();
    
            ui->rdo_btn_vertical->setStyleSheet(StyleSheetOn1); // On  LED
        }
        else
        {
            ui->rdo_btn_vertical->setStyleSheet(StyleSheetOff1); // Off LED
        }
    
    
    void MainWindow::startTimer()
    {
         timer.setSingleShot(true);
         timer.start(500); // 500ms
    
    }
    


  • @SruDom said in How to implement a time delay:

    I did something like this, and it works

    Your solution is a little hacky, as this is not how timers are intended to be used. What your code actually does is that the LED will be turned on immediately for a fraction of a second and then immediately turned off again.

    What you should do is connect the timeout() signal of the QTimer to your own slot which then turns the LED on. This would also eliminate the check for timer.isActive() which I would replace with another boolean to not restart the timer while the LED is already on.

    BTW, the radio button has a checked state and you can specify a single stylesheet which distinguishes between the checked and unchecked state. The stylesheet would need to be only set once. This is what your code would then look like (together with the suggestion I made above):

    if(a_vertical > onThreshold)
    {
        if(!ui->rdo_btn_vertical->isChecked())
            emit startTime();
    }
    else
    {
        ui->rdo_btn_vertical->setChecked(false);
    }
    

    Inside your timeout slot you then call ui->rdo_btn_vertical->setChecked(true).


Log in to reply