QT do while loop

匆匆过客 提交于 2020-01-06 07:11:43

问题


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 randnum 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 !


回答1:


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.




回答2:


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.




回答3:


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().




回答4:


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.



来源:https://stackoverflow.com/questions/5700403/qt-do-while-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!