简体   繁体   English

qt通过将对象移动到线程来跨线程发出信号

[英]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. 我正在寻找正确的模式以在基于Qt的应用中将其用于异步处理。

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 在删除线程的东西(moveTOThread)的情况下,一切正常,但我更喜欢在不同线程的事件循环中进行处理

According to the doc : 根据文档

Constructs a new QThread to manage a new thread. 构造一个新的QThread来管理一个新线程。 The parent takes ownership of the QThread. 父级拥有QThread的所有权。 The thread does not begin executing until start() is called. 在调用start()之前,线程不会开始执行。

Do you call method start , like this? 您是否这样调用方法start

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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