anarchy99
anarchy99

Reputation: 1023

How to Break an Infinite Loop using QPushButton?

I have an infinite loop, inside the loop I want to insert a state whenever I click a button, it will break the current loop. I've tried several ways like:

if(ui->btnStop->isDown())
  {
     break;
  }


if(ui->btnStop->isChecked())
      {
         break;
      }

and

if(cv::waitKey(10)>=0)
{
    break;
}

But, it doesn't work. I wonder why cv::waitKey doesn't work in Qt, but in a non-Qt project it will work flawlessly. Are there any other way to break an infinite loop with a QPushButton? Any help would be appreciated.

Upvotes: 1

Views: 4188

Answers (1)

cmannett85
cmannett85

Reputation: 22366

It doesn't work because the event processor cannot run whilst execution is locked in your loop. The easiest solution is to simply call QApplication::processEvents() in each loop, this will force the event processor to run.

//  Add a boolean to your class, and a slot to set it.
MyClass
{
    ...
private slots:
    void killLoop() { killLoopFlag_ = true; }

private:
    bool killLoopFlag_;
}

// In the constructor, connect the button to the slot.
connect( ui->btnStop, SIGNAL( clicked() ),
         this, SLOT( killLoop ) );

//  Then when performing the loop, force events to be processed and then
//  check the flag state.
killLoopFlag_ = false;
while ( true ) {
    //  ...Do some stuff.
    QApplication::processEvents();
    if ( killLoopFlag_ ) {
        break;
    }
}

However you need to ask yourself: Should I be doing long running calculations inside the GUI thread? The answer is usually no.

Upvotes: 3

Related Questions