View Full Version : Multiple QEventLoops in the MainThread QtGui

15th May 2014, 12:01
Hi all,

I have some Problems (perhaps some missunderstood) with multiple QEventLoops in the MainThread. First of all the reason how I got to this problems ;)
Some pseudo code (wont compile)...

void example::method1(){
/** this pseudo code shows a simple use of qsqlquery and executes 2 select statements (2nd select use the result value from qry1)
QSqlQuery qry("Select col1, col2 from tbl where id = 5");
qry.exec("Select col3 from tbl2 where id = qry.value(0).toInt()....);
qDebug() << "value col3 tbl2 with id=5 from tbl1" << qry.value(0);
So far so good, now i have written a simple sqlquery class with signal slot to execute queries not blocking the main gui thread...

void example::method2(){
// Pseudo code
SqlQuery qry("Select...);
connect thread started to qry execute, and the signal qry finished() with slot: example::method3(...)
void example::method3(...){
//use the result from qry execute method2 and execute a new qry with the result...
Sqlqry ("select.... );


As good as Signal/Slots are, the Problem in example2 is that it will become really hard to read if u normally use multiple qry.execute() in one method() and now with multiple slots/methods...

So I thought about writing a "wrapper" for the SqlQuery class...
The Problem is that I have to start a QEventLoop(in the main thread) to wait for the qry result and the other Problem is that if I trigger another qry while an EventLoop(created in the MainThread by the wrapper) hasn´t finished yet (waiting for the qry to be finished), another Eventloop will be created in the main thread and the first created Eventloop will be left after the 2nd created Eventloop has finished (First in Last Out...). So If I would start a qry which took 5 seconds and start another qry while the first still running and the second one would take 20 seconds, all the results would be available after 20 seconds (The first qry has finished after 5 seconds but the 2nd eventloop hasn´t quit yet so I have to wait 20 seconds till the results are there/available in the main thread...)

Sorry for the long and perhaps confusing description ... :(

I dont have any ideas how to solve my small Problem. (use threaded Sqlquery without rewriting/change the default useage...)
I am really thankful for any ideas ;)

Wish u all a nice day.


15th May 2014, 14:05
Your main thread usually runs an event loop. QApplication::exec() starts it.

I am afraid I don't understand why you separate the sequence into different slots and not just have all queries within one slot.

It also looks like what you are actually looking for it either implementing QThread::run() or QThreadPool+QRunnable subclasses