lundi 16 décembre 2019

Cross thread signal-slot involving QThreadPool doesn't work

I wrote a small program with the intention that a subclass of QRunnable, running on a thread started by QThreadPool, would signal to a subclass of QObject running on the main thread. The signal is sent, but somehow the slot function is not triggered?

//main.hpp
#ifndef MAIN_HPP
#define MAIN_HPP

#include <QObject>
#include <QRunnable>
#include <QThreadPool>
#include <iostream>

class SIG : public QObject, public QRunnable
{
  Q_OBJECT

  signals:
    void my_signal();

  public:
    SIG() = default;
    virtual ~SIG(){};

    void run()
    {
      std::cout << "running!" << std::endl;
      emit my_signal();
    };
};

class SLO: public QObject
{
  Q_OBJECT

  public:
      SLO() = default;
      virtual ~SLO(){};
    public slots:
      void my_slot()
        {
          std::cout << "signal received!" << std::endl;
        };
};

#endif // MAIN_HPP

//main.cpp
#include "main.hpp"

int main(int argc, char *argv[])
{
    QThreadPool *pool = QThreadPool::globalInstance();
    SIG *sig = new SIG();
    SLO *slo = new SLO();
    QObject::connect( sig, &SIG::my_signal,
                      slo, &SLO::my_slot );
    pool->start( sig );
}

Program output is as follows:

Starting /home/work/build-exp_thread_sig_slot-Desktop_Qt_5_10_0_GCC_64bit-Debug/exp...

running!

/home/work/build-exp_thread_sig_slot-Desktop_Qt_5_10_0_GCC_64bit-Debug/exp exited with code 0

Why is the SLO::my_slot function not triggered?

Aucun commentaire:

Enregistrer un commentaire