QT do while loop
I am learning QT these days and I wanted to test do while loop , the actual login works in normally, but in QT the application freezes .. I have defined r开发者_开发问答andnum and guess in the header file ( public )
void MainWindow::on_pushButton_clicked()
{
srand (time(NULL));
randnum = rand() % 10 +1;
do {
guess = ui->spinBox->value();
if (guess < randnum)
{
ui->label->setText("try something big");
}
else if (guess > randnum)
{
ui->label->setText("try something small");
}
else
ui->label->setText("YAY?");
} while (guess != randnum);
}
please tell me how to find the reason why it freezes.. thanks !
Your application freezes because you are looping and never letting Qt do its necessary processing.
You need to set up what the random guess is in the class constructor and then on on the on_pushButton_clicked call you need to just do the if checks. ie remove the do while loop.
The code will exit the callback function and then control will return to Qt allowing the user to take another guess.
I am not a QT expert, but if the spinbox value is not correct, you will loop endlessly in this function and the user has no possibility of clicking the spinbox again. Just remove the loop and set randnum
somewhere in the class constructor, things should be fine then.
The QT event loop will take care of keeping your program alive, no need for you to do it.
If you have made an incorrect guess (i.e. guess != randnum) then you will reenter the while loop indefinitely ... i.e. there is no break. You need to only check the guess upon receiving a QSpinBox::valueChanged()
.
Tell Qt to process events by calling QCoreApplication::processEvents() if the user didn't pick the correct number.
Better solution would be to do what Goz suggested and I strongly recommend doing it that way.
精彩评论