[Qt-interest] Break an infinite loop in the qt event loop.

Oliver.Knoll at comit.ch Oliver.Knoll at comit.ch
Tue Aug 24 10:02:17 CEST 2010


On 2010-08-24 Thiago Thiago Macieira wrote:

> ...
> 	while (condition) {
> 		/* Do something */
> 		processEvents();
> 	}
> 
> And make sure that condition changes from true to false when the loop 
> must be broken.
> 
> Note that the "Do something" part should be fast so that the GUI doesn't block.

And if that "Do something" takes longer, then put the whole thing into a QThread, and if the user hits "Cancel" then signal the thread to terminate by setting the 'condition' to false - then synchronise with the thread (wait until it has finished), see QThread documentation how to "nicely" terminate a thread (if the work is not "critical" (no data corruption can happen or it is not so bad if data corruption happens) then in theory you could also instantly kill() a thread - but that is very rude and usually not a good practice).

Like this the GUI should remain responsive (if the thread has a low enough priority and does not eat up the CPU ;) - in the worst case the user would have to wait a couple of moments, until processEvents() finishes (and eventually the thread).

As always keep in mind that GUI operations and painting (to widgets) must ONLY happen in the "main thread" (or the one where the QApplication object "lives" in) - if you need to do painting, send asynchronous signals to the main event loop (keyword: "queued signals" - check Qt docs), and let the main thread do the painting.

Cheers, Oliver
--
Oliver Knoll
Dipl. Informatik-Ing. ETH
COMIT AG - ++41 79 520 95 22






More information about the Qt-interest-old mailing list