我正在使用 Qt5,我通过 moveToThread() 将 QObject 工作线程传递给 QThread 的实例来实现线程。我的实现看起来像这样..
工人.h
class worker : public QObject
{
Q_OBJECT
public:
explicit worker(QObject *parent = 0);
bool IsWorkRunning();
void MoveObjectToThread();
signal:
void SignalToObj_mainThreadGUI();
public slots:
void do_Work();
void StopWork();
void StartWork();
private:
void Sleep();
QThread *workerthread;
volatile bool running,stopped;
};
工人.cpp
worker::worker(QObject *parent) :
QObject(parent),stopped(false),running(false)
{
}
void worker::do_Work()
{
running = true;
while(!stopped)
{
if(running)
{
emit SignalToObj_mainThreadGUI();
workerthread->msleep(20);
}
}
}
void worker::StopWork()
{
running = false;
}
void worker::StartWork()
{
running = true;
}
bool worker::IsWorkRunning()
{
return running;
}
void MoveObjectToThread()
{
workerthread = new QThread;
QObject::connect(workerthread,SIGNAL(started()),this,SLOT(do_Work()));
this->moveToThread(workerthread);
workerthread->start();
}
主窗口.h
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
signals:
void Startwork_mainwindow();
void Stopwork_mainwindow();
public slots:
private slots:
void on_pushButton_push_to_start_clicked();
void on_pushButton_push_to_stop_clicked();
private:
Ui::MainWindow *ui;
worker myWorker;
bool work_started;
};
主窗口.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),work_started(false),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QObject::connect(this,SIGNAL(Startwork_mainwindow()),&myWorker,SLOT(StartWork()));
QObject::connect(this,SIGNAL(Stopwork_mainwindow()),&myWorker,SLOT(StopWork()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_push_to_start_clicked()
{
if(!work_started)
{
myWorker.MoveObjectToThread();
work_started = true;
}
if(!myWorker.IsWorkRunning())
emit this->Startwork_mainwindow();
}
void MainWindow::on_pushButton_push_to_stop_clicked()
{
if(myWorker.IsWorkRunning())
emit this->Stopwork_mainwindow();
}
不知道为什么以下两个信号/插槽对似乎不起作用
QObject::connect(this,SIGNAL(Startwork_mainwindow()),&myWorker,SLOT(StartWork()));
QObject::connect(this,SIGNAL(Stopwork_mainwindow()),&myWorker,SLOT(StopWork()));
因此,一旦do_Work()
插槽被started()
QThread 对象的信号触发,我就无法启动或停止线程。仅供参考,我的这篇文章是我之前在这里描述的文章的延续。任何见解都会有所帮助......谢谢