0

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

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.