Home > Mobile >  Repeat indefinitely until a button is pressed in another window with C in QT
Repeat indefinitely until a button is pressed in another window with C in QT

Time:04-11

I am writing a program in C with qtcreator in which I have to execute some actions indefinitely until the user, in another window, wants to stop it by pressing a button. The problem I am having is that when I run the code, the new window is blank and the program goes into "not responding" mode even though the loop is still executing. Could you tell me how I can solve this?

void MainWindow::ejecutarModoDemo()
{

    this->md->show();
    this->md->setIniciar();
    //when pushbutton is clicked in the md window, it change to true
    while(!this->md->getTerminar()){
        srand(time(NULL));
        girarPlato(8   rand()%8);
        QThread::msleep(5000);
        tragarBola();
        while(obtenerSTA()!=1){
            QThread::msleep(1000);
        }
        QThread::msleep(2000);
        girarPlato(20   rand());
        lanzarBola(900   rand()`0);
        mostrarGanador();
    }
    detenerMotor();
    this->md->hide();

}

CodePudding user response:

QThread::msleep sleeps for a certain time, it's what's called "busy waiting". For the GUI to be responsive, it has to be able to process events (paint event etc.). In Qt, you can do this two ways:

  • Either implicitly by calling QApplication::exec() (which internally runs an event loop for you), or
  • by explicitly calling QCoreApplication::processEvents()

Typically, computations that take a while should run in a separate background thread, not in the GUI thread. For a "quick fix", you might get away with QCoreApplication::processEvents() in between computation steps; but you need to make sure that the single steps of the computation are very short then; let's say less than 100ms.

Reacting on the press of a button in Qt typically happens with the signal-slot mechanism.

  • Related