Qt之线程与数据传递的使用

// .h
class Demo : public QObject
{
    Q_OBJECT
public:
    Demo();
    void start();
public slots:
    void run() {
    start();
    }
signals:
    void send(QJsonObject);
};

// .cpp
Demo::Demo()
{
}

void Demo::start()
{
    QJsonObject a = readJson("/demo.json");
    if (a.isEmpty()) {
    return;
    }
    emit control(a);
}

// QtWindow.cpp
void QtWindow::recv(QJsonObject _json) 
{
    // ...
}

// 启动线程(当前是在QtWindow)
Demo *demo = new Demo();
QObject::connect(demo, SIGNAL(send(QJsonObject)), this, SLOT(recv(QJsonObject)));
QThread *thread = new QThread();
demo->moveToThread(thread);
thread->start();
QObject::connect(thread, SIGNAL(started()), demo, SLOT(run()));

// .h
class Demo : public QRunnable
{
public:
    Demo();
    virtual ~Demo();
    void run();
    void setWindow(QtWindow*);
    QtWindow *m_window;
};

// .cpp
Demo::Demo()
{
}

Demo::~Demo()
{

}

void Demo::setWindow(QtWindow *_m_window)
{
    m_window = _m_window;
}

void Demo::run()
{
    /* 发送指令 ... */
    QMetaObject::invokeMethod(m_window, "recv", Q_ARG(QJsonObject, m_json));
}

// QtWindow.cpp
void QtWindow::recv(QJsonObject _m_json) 
{
    // ...
}

// 启动线程(当前是在QtWindow)
Demo *demo = new Demo();
demo.setWindow(this);
QThreadPool::globalInstance()->start(demo);