或者Controller.h:
#ifndef CONTROLLER_H
#define CONTROLLER_H
#include <QObject>
#include <QThread>
class Controller : public QObject
{
Q_OBJECT
QThread workerThread;
public:
Controller(QObject *parent = 0);
~Controller();
public slots:
void handleResults(const QString &str);
signals:
void operate(const QString &str);
};
#endif // CONTROLLER_H
controller.cpp:
#include "controller.h"
#include <QDebug>
#include "worker.h"
Controller::Controller(QObject *parent) : QObject(parent), workerThread()
{
Worker *worker = new Worker;
connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
connect(this, &Controller::operate, worker, &Worker::doWork, Qt::QueuedConnection);
connect(worker, &Worker::resultReady, this, &Controller::handleResults, Qt::QueuedConnection);
worker->moveToThread(&workerThread);
workerThread.start();
}
Controller::~Controller()
{
workerThread.quit();
workerThread.wait();
}
void Controller::handleResults(const QString &str)
{
qDebug()<<"handleResult:"<<str;
}
worker.h:
#ifndef WORKER_H
#define WORKER_H
#include <QObject>
#include <QThread>
#include <QDebug>
class Worker : public QObject
{
Q_OBJECT
public:
public slots:
void doWork(const QString ¶meter);
signals:
void resultReady(const QString &result);
};
#endif // WORKER_H
worker.cpp:
#include "worker.h"
#include <QDebug>
void Worker::doWork(const QString ¶meter) {
/* ... here is the expensive or blocking operation ... */
qDebug()<<"doWork:"<<parameter;
emit resultReady(parameter);
}
main.cpp中:
#include <QCoreApplication>
#include "worker.h"
#include <QTimer>
#include <QEvent>
#include "controller.h"
int main(int argc, char*argv[])
{
QCoreApplication app(argc, argv);
Controller con;
while(1)
{
QString str = "hello";
emit con.operate(str);
QThread::sleep(1);
}
return app.exec();
}
我想通过操作信号调用doWork插槽功能,在执行doWork功能之前会发出resultReady信号,但不会执行插槽函数handleResults。
函数可以调用doWork,但为什么插槽handleResults没有被调用?