在我的简单示例代码中,有一个开始和停止按钮以及一个计数器。当您按下开始时,会创建一个线程并递增计数器,直到您按下停止。点击事件都在工作,但是从 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);
}
}
谢谢!