Please nominate your Qt Champions for 2021!

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 {
       Slave* slave;
          void startSlave();
          void init() {
             slave = new Slave(this);
             emit startSlave();
    class Slave : public QObject {
       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?


  • Lifetime Qt Champion

    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.

  • Moderators

    @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.

Log in to reply