Home > Mobile >  How to use a button to stop a while loop that has a sleep timer? (Qt c )
How to use a button to stop a while loop that has a sleep timer? (Qt c )

Time:05-06

I would like to preface that I am very new to programming. So the answer may be obvious or I may have done something incorrectly; feel free to (politely) point that out. I am always excited to learn and be better!

I am trying to create and send test data using a while loop. The while loop has a sleep timer so that the data is only sent once per second. I would like the stop button to immediately stop the data from being sent (and disable the button) but because of the sleep timer, there is a lag between when the button is clicked and when the function is executed.

Here is what I have:


    void DlgTestData::on_btnStart_clicked()
    {
        ui->btnStart->setEnabled(false);
        ui->btnStop->setEnabled(true);
    
        m_bSendingData = true; 
    
        while ( m_bSendingData ) 
        {
            CreateAndSendTestData(); //Only sends a single message
            QThread::sleep(1`enter code here`)
        }
    }
    
    void DlgTestData::on_btnStop_clicked()
    {
        m_bSendingData = false;
        ui->btnStart->setEnabled(true);
        ui->btnStop->setEnabled(false);
    }

CodePudding user response:

Use a QTimer instead of a sleep. That way it can be stopped at any point, and it doesn't block other things that your application wants to do while it's waiting.

Make the QTimer a member pointer of your class:

class DlgTestData
{
   ...
private:
    QTimer *m_timer;
};

Then initialize it in the constructor:

DlgTestData::DlgTestData()
{
    ...
    // Create, but don't start the timer
    m_Timer = new QTimer(this);
    connect(m_timer, &QTimer::timeout, this, &DlgTestData::CreateAndSendTestData);
}

When your start button is pressed, simply start the timer.

void DlgTestData::on_btnStart_clicked()
{
    ...
    m_timer->start(1000);
}

And then when the stop button is pressed, simply stop the timer.

void DlgTestData::on_btnStop_clicked()
{
    ...
    m_timer.stop();
}
  •  Tags:  
  • c qt
  • Related