#ifndef TEST_H
#define TEST_H

#include <QObject>
#include <QDebug>
#include <QThread>
#include <unistd.h>

class Child1 : public QObject
{
    Q_OBJECT
public:
    void test()
    {
        qDebug() << "A in thread:" << QThread::currentThread();
        emit sigSleep();
        sleep(5);
        qDebug() << "finish A";
    }
signals:
    void sigSleep();
};

class Child2 : public QObject
{
    Q_OBJECT
public slots:
    void slotSleep()
    {
        qDebug() << "B in thread:" << QThread::currentThread();
        sleep(10);
        qDebug() << "finish B";
    }
};

class Parent : public QObject
{
    Q_OBJECT
public:
    Parent()
        :A()
        ,B()
    {
        connect(&A, &Child1::sigSleep, &B, &Child2::slotSleep);
        A.test();
    }

private:
    Child1 A;
    Child2 B;
};

#endif // TEST_H
#include "mainwindow.h"
#include <QApplication>

#include "test.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    Parent p;

    return a.exec();
}

运行结果:

A in thread: QThread(0x614240)

B in thread: QThread(0x614240)

finish B

finish A

 

槽函数执行时,原函数和槽函数在同一个线程中。

原函数sleep5秒,槽函数sleep10秒,但是槽函数先执行,而且总计时间是15秒。所以,槽函数执行时,原函数没有继续执行,等待槽函数执行完成时才执行?

猜测是通过类似于调用function / bind的原理,在emit信号处调用信号绑定的对应function / bind?