Solved Run long task in the background with signal slot mechanism
-
Hi,
I have got a problem with signal slot mechanism. I have written a little code snippet which representatives my problem.
My main problem is: i have got a long operation in Slave::onStartSlave() and i would not like to freeze my Boss::init() method.
So i want to run Slave::onStartSlave() in the background because it is a long process.
When i emit startSlave in Boss::init method , the actual thread ID is the same as when i step into Slave::onStartSlave method .class Boss : public QObject { Q_OBJECT Slave* slave; signals: void startSlave(); public: void init() { slave = new Slave(this); emit startSlave(); ... } } class Slave : public QObject { Q_OBJECT Slave(Boss* boss){ connect(boss, &Boss::startSlave, this, &Slave::onStartSlave); } public slots: void onStartSlave(); }
How can i solve this?
Is signal-slot mechanism is the right solution for it?
Maybe i should use QThread?Br,
Peter -
@pvt.peter
Yes using a thread would be the right way if init() is long process.Its not a signal&slot issue as such.
Long loops will kill/starve the event loop.
This can sometimes be countered calling processevents but its not recommended as it's
not nice design and in many cases not even a full solution.So go for the tread as long operations are not good to have in the GUI thread as they lag the app alot.
https://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/
-
@pvt.peter to add to @mrjj , if it's a one time shot and forget thing you want to run 'threaded' than QtConcurrent might be easier to setup and use and worth looking into.
-
Hi @mrjj, thanks for your reply.