Threads & Event loop in the Qt application [closed] Threads & Event loop in the Qt application [closed] multithreading multithreading

Threads & Event loop in the Qt application [closed]


Each thread processes its own event loop, you normally do not need to worry about this - its taken care of for you and unless you have a specific reason to its meant to be left alone.

QThread is a class provided by Qt for you to use to control the operation of a thread. The method of "putting" object into that thread is to use the moveToThread() function.

You should not inherit the QThread class in order to run some code inside a thread (use the moveToThread function), the only reason to inherit the QThread class is if you want to change the behaviour of the thread control.

Below are the basic steps to get an object running inside a thread:

MyObj *myObj = new MyObj(0); // 0 = no parent if your object inherits QObjectQThread* thread = new QThread;myObj->moveToThread(thread);QObject::connect(thread, SIGNAL(started()), myObj, SLOT(run()));thread->start();

Once you call start() the thread will start and emit the started signal, your object will receive it and process it in its slot/function run().

Note: your thread does not end when the function/slot run() inside your object ends (so you do not need to do a "forever" loop). The thread only stops when you tell it to quit (or destroy it), this means your thread can be idle until it receives a signal or event - this is where the event loop comes in - incoming events are handled by the event loop within the QThread class.

Note: also this code is a snippet - it does not deal with the shutting down of the thread, there are other "template" bits of code that you can use for this.

Edit

So events are handled by the event queue (things like mouse click events all of base type QEvent) - used more by the system where some events may trigger signals (onClicked for example). Signals and slots are a different mechanism that is used more by the user where you handle these in your slots using the connect() function. Here is a better explanation then I could come up with: see here


Start reading here for some basic information and here for the complete information.