QT non-blocking hang

In the Qt program, sometimes it is necessary to wait for a certain condition to be satisfied within a certain period of time, but it cannot wait in a blocking manner, otherwise the interface will be stuck and cannot respond to other operations of the user. In this case, you can use the non-blocking suspend method provided by Qt, as follows:

void nonBlockingPause(int ms)
{
    
    
    QEventLoop loop;
    QTimer timer;
    timer.setInterval(ms);
    timer.setSingleShot(true);
    QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
    timer.start();
    loop.exec();
}

In the above code, we created a QEventLoop object to implement non-blocking pending operations. Then use the QTimer object to set the waiting time. When the time is up, the timeout() signal will be triggered and the event loop will exit (implemented by the QEventLoop::quit() method). Finally, call the exec() method of QEventLoop to start the event loop, and enter the suspended state, and will not wake up until the timeout() signal is triggered.

The non-blocking suspend method can be applied to some time-consuming operations, such as network requests, timers, etc., to improve user experience. It should be noted that in some scenarios, using this method may cause some unpredictable problems, such as infinite loops and high CPU usage. Therefore, it should be used with caution and adjusted according to the actual situation.

Guess you like

Origin blog.csdn.net/qq_42629529/article/details/131007529