qt 通过将对象移动到

qt emitting a signal across threads by moving the object to

我正在寻找在基于 Qt 的应用程序中使用它进行异步处理的正确模式。

这是一个简化的class,它应该接收信号

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

    // ...
    }
};

此 class 实例的创建是动态的(实际上也是简化的 - 用于消息处理的对象数组)。

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

main函数中也存在一个注册:

    qRegisterMetaType<Message> ("Message");

问题是为什么永远不会调用插槽? 如果删除 Thread 东西(moveTOThread)那么一切正常, 但我更喜欢在不同线程的事件循环中进行处理

根据 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.

你是这样调用方法start的吗?

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