Multithreading – threads and event loops in QT applications
Anyone can explain the differences between threads and event loops and how to use it in QT applications
Where can I use the move to thread and complete the thread class?
Solution
Each thread handles its own event loop, and you usually don't need to worry about it - it will take care of you unless you have a specific reason to let it exist alone
Qthread is a class provided by QT to control thread operation The method to "put" an object into the thread is to use the movetothread() function
You should not inherit the qthread class to run some code within the thread (using the movetothread function). The only reason to inherit the qthread class is that you want to change the behavior of the thread control
The following are the basic steps for running objects within a thread:
MyObj *myObj = new MyObj(0); // 0 = no parent if your object inherits QObject QThread* thread = new QThread; myObj->moveToThread(thread); QObject::connect(thread,SIGNAL(started()),myObj,SLOT(run())); thread->start();
Once start () is called, the thread starts and sends a start signal, and your object will receive it and process it in its slot / function run ()
Note: when the function / slot run () in the object ends, your thread will not end (so you don't need to execute a "permanent" loop) The thread only stops when you tell it to quit (or destroy it), which means that your thread can be idle until it receives a signal or event - this is where the event loop enters - the incoming event is handled by the event loop. The qthread class
Note: this code is also a fragment - it does not handle thread shutdown, and there are other "template" code available for this
edit
Therefore, events are handled by the event queue (such as mouse click events of all basic types of qevent) – the system uses more events, some of which can trigger signals (such as onclicked) Signals and slots are different mechanisms. Users can use the connect() function to process these mechanisms in slots This is a better explanation, and then I can think of: see here