简体   繁体   中英

Qt signal slot with threads

I have a problem with signal/slots in a QThread class. 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. 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 :

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.

Signals sent to a QThread object will go to the thread of the parent object. 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";
    }
};

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