Qt:多线程连接不工作

Qt: Multithreading connect does not work

本文关键字:工作 连接 多线程 Qt      更新时间:2023-10-16

我想连接两个线程。一个线程是我的应用程序的主线程,另一个是工作线程。我的代码基于以下示例doc.qt.io/qt-5/。对我来说,这并不完全有效。我正在发送一个QString到我的WorkerThread(这工作),并希望将其发送回主线程(不工作)。在问我为什么这么做之前,这只是一个非常简单的例子。真正的代码要复杂得多,但我有完全相同的问题。如果这些例子能运行,我很确定复杂的例子也能运行。下面的代码是:

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

谢谢你的帮助。

就像你在header中定义Slot/Signal一样:

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

你也应该像这样在你的connect中使用它们:

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


相关文章: