我是 StackOverflow 的新手,想知道我是否做得对:
我正在编写一个简单的 Qt 应用程序来测试多线程(我也是全新的)。我创建了一个包含小部件的 MainWindow,以及一个子类 QThread 并覆盖 run() 方法的类 MyThread。
该应用程序只显示两个按钮,“开始计数器”和“停止计数器”,以及一个文本字段。当按下“开始计数器”时,会创建一个工作线程并在后台运行,在 while 循环中不断增加一个计数器,并向主线程(GUI 所在的位置)发出更新值的信号。当按下“停止计数器”时,会向主线程发送一个信号以停止 while 循环,并停止计数器,直到再次按下“开始计数器”。
这工作得很好......但这是最好的方法吗?我对此很陌生,并且读过很多人说“不要子类 QThread”和其他人说“子类 QThread”,这有点令人困惑。如果这不是实现这类事情的最佳方式(在带有“开始”和“停止”按钮的后台线程中运行计算密集型循环),那是什么?如果我做错了,我该如何做对?我不想学习错误的方法。
谢谢!这是代码:
我的线程.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QMutex>
class MyThread : public QThread
{
Q_OBJECT
public slots:
void stopRunning();
protected:
virtual void run();
signals:
void signalValueUpdated(QString);
private:
bool isRunning;
};
我的线程.cpp
#include "MyThread.h"
#include <QString>
void MyThread::run()
{
qDebug("Thread id inside run %d",(int)QThread::currentThreadId());
static int value=0; //If this is not static, then it is reset to 0 every time this function is called.
isRunning = 1;
while(isRunning == 1)
{
QString string = QString("value: %1").arg(value++);
sleep(1/1000); //If this isn't here, the counter increments way too fast and dies, or something; the app freezes, anyway.
emit signalValueUpdated(string);
}
}
void MyThread::stopRunning()
{
isRunning = 0;
}
主窗口.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QApplication>
#include <QPushButton>
#include <QHBoxLayout>
#include <QLineEdit>
#include "MyThread.h"
class MainWindow : public QWidget
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
private:
//Widgets
QHBoxLayout * boxLayout;
QPushButton * startButton;
QPushButton * stopButton;
QLineEdit * lineEdit;
MyThread thread;
};
#endif
主窗口.cpp
#include "MainWindow.h"
MainWindow::MainWindow(QWidget *parent) : QWidget(parent)
{
boxLayout = new QHBoxLayout(this);
startButton = new QPushButton("Start Counter", this);
stopButton = new QPushButton("Stop Counter", this);
lineEdit = new QLineEdit(this);
boxLayout->addWidget(startButton);
boxLayout->addWidget(stopButton);
boxLayout->addWidget(lineEdit);
qDebug("Thread id %d",(int)QThread::currentThreadId());
//When the start button is pressed, invoke the start() method in the counter thread
QObject::connect(startButton,SIGNAL(clicked()),&thread,SLOT(start()), Qt::QueuedConnection);
//When the stop button is pressed, invoke the stop() method in the counter thread
QObject::connect(stopButton,SIGNAL(clicked()),&thread,SLOT(stopRunning()), Qt::QueuedConnection);
//When the counter thread emits a signal saying its value has been updated, reflect that change in the lineEdit field.
QObject::connect(&thread,SIGNAL(signalValueUpdated(const QString&)),lineEdit,SLOT(setText(const QString&)), Qt::QueuedConnection);
}