在我的简单示例代码中,有一个开始和停止按钮以及一个计数器。当您按下开始时,将创建一个线程并递增计数器直到您按下停止。单击事件都在工作,但从 dialog.cpp 调用时线程本身不会启动,并且计数器从不递增。有什么想法吗??
代码来自这个人的教程,与他在这里所做的完全一样,他的工作:http://www.voidrealms.com/viewtutorial.aspx?id=79
对话框.h
#ifndef DIALOG_H
#define DIALOG_H
#include "mythread.h"
#include <QDialog>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
MyThread *mThread;
private:
Ui::Dialog *ui;
public slots:
void onNumberChanged(int);
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
};
#endif // DIALOG_H
对话框.cpp
#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
mThread = new MyThread(this);
connect(mThread,SIGNAL(NumberChanged(int)), this, SLOT(onNumberChanged(int)));
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::onNumberChanged(int Number){
ui->label->setText(QString::number(Number));
}
void Dialog::on_pushButton_clicked()
{
mThread->start();
}
void Dialog::on_pushButton_2_clicked()
{
mThread->Stop = true;
}
我的线程.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = 0);
void run();
bool Stop;
signals:
void NumberChanged(int);
public slots:
};
#endif // MYTHREAD_H
我的线程.cpp
#include "mythread.h"
#include <QtCore>
MyThread::MyThread(QObject *parent) :
QThread(parent)
{
}
void MyThread::run() {
for (int i = 0; i < 100000; i++) {
QMutex mutex;
mutex.lock();
if (this->Stop) break;
mutex.unlock();
emit NumberChanged(i);
}
}
谢谢!
最佳答案
在查看您链接的网站中的示例代码后,我发现至少有两个问题:
1) Stop
成员变量未初始化使用,将构造函数更改为如下所示应该可以解决您的主要问题:
MyThread::MyThread(QObject *parent) :
QThread(parent),
Stop(false)
{
}
2) Stop
变量永远不会被重置,所以按下开始/停止按钮只能工作一次。如果 break 语句也重置标志,效果会更好:
if (this->Stop)
{
Stop = false;
break;
}
关于c++ - 我想弄清楚如何在简单的 Qt gui 应用程序中使用线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12920336/