Qt:多线程连接不起作用

时间:2016-09-08 13:53:51

标签: c++ multithreading qt

我想连接两个线程。 One Thread是我的应用程序的Mainthread,另一个是workerthread。我的代码基于以下示例doc.qt.io/qt-5/。对我来说,它并不完全有效。我正在向我的WorkerThread发送一个QString(这个工作),然后想要将它发送回MainThread(不起作用)。在问我为什么这样做之前,这只是一个非常简单的例子。真正的代码要复杂得多,但我有完全相同的问题。如果这些例子会运行,我非常肯定复杂的例子也会起作用。代码如下:

Main.cpp的

#include "Controller_C.h"
#include <QtWidgets/QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Controller_C Controller;
    Controller.SendData("Hello World!");
    return a.exec();
}

Controller_C.cpp

#include "Controller_C.h"
#include <qmessagebox.h>

Controller_C::Controller_C(QWidget *parent)
    : QMainWindow(parent),
      Worker(new Worker_C())
{
    ui.setupUi(this);

    Worker->moveToThread(&WorkerThread);
    connect(&WorkerThread, SIGNAL(started()), this, SLOT(ThreadStarted()));
    connect(this, SIGNAL(SendToWorker(QString)), Worker, SLOT(DoWork(QString)));
    connect(Worker, SIGNAL(SendToController()), this, SLOT(ReceiveData()));
    WorkerThread.start();
}

Controller_C::~Controller_C()
{

}

void Controller_C::SendData(QString aString)
{
    QThread* Controller = QThread::currentThread();
    QMessageBox::information(this, "Info", QString("We have send the following to the Worker Thread: %1").arg(aString));
    emit SendToWorker(aString);
}

void Controller_C::ReceiveData(QString aString)
{
    QThread* Controller = QThread::currentThread();
    QMessageBox::information(this, "Info", QString("The Controller received the following: %1").arg(aString));
}

Controller_C.h

#ifndef CONTROLLER_C_H
#define CONTROLLER_C_H

#include <QtWidgets/QMainWindow>
#include "ui_Controller_C.h"
#include "Worker_C.h"
#include <qthread.h>

class Controller_C : public QMainWindow
{
    Q_OBJECT

public:
    Controller_C(QWidget *parent = 0);
    ~Controller_C();

    void SendData(QString aString);

private:
    Ui::Qt_TestEnvironmentClass     ui;
    Worker_C*                       Worker;
    QThread                         WorkerThread;

signals:

    void SendToWorker(QString);

public slots:

    void ReceiveData(QString aString);
};

#endif // CONTROLLER_C_H

Worker_C.cpp

#include "Worker_C.h"
#include <qmessagebox.h>
#include <qthread.h>

Worker_C::Worker_C()
{

}

Worker_C::~Worker_C()
{

}

void Worker_C::DoWork(QString aString)
{
    QThread* Worker = QThread::currentThread();
    emit SendToController(aString);
}

Worker_C.h

#ifndef WORKER_C_H
#define WORKER_C_H

#include <QObject>

class Worker_C : public QObject
{
    Q_OBJECT

public:
    Worker_C();
    ~Worker_C();

public slots:

    void DoWork(QString aString);

signals:

    void SendToController(QString);

};

#endif // WORKER_C_H

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

就像你在标题中定义Slot / Signal的方式一样:

  

void ReceiveData(QString aString);
  void SendToController(QString);

你也应该在你的连接中使用它们:

connect(Worker, SIGNAL(SendToController(QString)), this, SLOT(ReceiveData(QString)));`