简体   繁体   中英

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM