Search code examples
c++multithreadingqtsignals-slots

qt emitting a signal across threads by moving the object to


I'm looking for correct pattern to use it in Qt-based app for async processing.

this is a simplified class which should receive a signals

class Receiver : public QObject {
    Q_OBJECT
public:
    explicit Receiver(QObject *parent = nullptr) : QObject(parent) {    }
public slots:
    void onNewMessage(Message message) {

    // ...
    }
};

the creating of the instance of this class is a dynamic (also simplifed, really - an array of the objects for message processing).

    Receiver* r;
    // ...
    if (r == nullptr) {
        r = new Receiver{};
        r->moveToThread(new QThread);
        connect(this, &MessageGenerator::messageCompleted, r, &Receiver::onNewMessage);
    }

in main function also exists a registration:

    qRegisterMetaType<Message> ("Message");

the question is why slot is never called? in case of the removing Thread stuff (moveTOThread) then all works fine , but I'd prefer to have a processing in event loops in different threads


Solution

  • According to the doc:

    Constructs a new QThread to manage a new thread. The parent takes ownership of the QThread. The thread does not begin executing until start() is called.

    Do you call method start, like this?

    r = new Receiver{};
    t = new QThread();
    r->moveToThread(t);
    connect(this, &MessageGenerator::messageCompleted, r, &Receiver::onNewMessage);
    t->start();