简体   繁体   English

带线程的 Qt 信号槽

[英]Qt signal slot with threads

I have a problem with signal/slots in a QThread class. QThread 类中的信号/插槽有问题。 My design looks like this:我的设计是这样的:

class Manager : public QObject {
    Q_OBJECT
public:
    Manager(QObject* parent) : QObject(parent) {
        Thread thread* = new Thread(this);
        connect(this, SIGNAL(testsignal()), thread, SLOT(test()));
        thread->start();

        ...

        emit testsignal();
    }
signals:
    void testsignal();
};

class Thread : public QThread {
    Q_OBJECT
public slots:
    void test() {
        qDebug() << "TEST";
    }
private:
    void run() {}
};

The signal never reaches my test() method.信号永远不会到达我的 test() 方法。 Can someone help?有人可以帮忙吗? Thanks.谢谢。

The problem is that sending signals across threads results in queuing the signal into the target thread's event queue (a queued connection).问题是跨线程发送信号会导致将信号排入目标线程的事件队列(排队连接)。 If that thread never processes events, it'll never get the signal.如果该线程从不处理事件,它将永远不会收到信号。

Also, according to the QThread::run documentation :另外,根据QThread::run文档

Returning from this method will end the execution of the thread.从此方法返回将结束线程的执行。

In other words, having an empty run method results in instant termination of the thread, so you're sending a signal to a dead thread.换句话说,拥有一个空的run方法会导致线程立即终止,因此您正在向死线程发送信号。

Signals sent to a QThread object will go to the thread of the parent object.发送到 QThread 对象的信号将转到父对象的线程。 In this case to the same thread that created it .在这种情况下,创建它同一个线程

To have a object live on another thread you should move it to that thread:要让一个对象存在于另一个线程上,您应该将其移动到该线程:

class Manager : public QObject {
    Q_OBJECT
public:
    Manager(QObject* parent) : QObject(parent) {
        Thread thread* = new QThread(this);
        Receiver* rec = new Receiver(); //no parent
        connect(this, SIGNAL(testsignal()), rec, SLOT(test()));
        connect(thread, SIGNAL(finished()), rec, SLOT(deleteLater()));
        rec->moveToThread(thread);
        thread->start();

        ...

        emit testsignal();
    }
signals:
    void testsignal();
};

class Receiver: public QObject {
    Q_OBJECT
public slots:
    void test() {
        qDebug() << "TEST";
    }
};

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

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