Qt中创建线程的方法:
只需要子类化QThread并重新实现它的run()函数就可以了。run()是个纯虚函数,是线程执行的入口,在run()里出现的代码将会在另外线程中被执行。run()函数是通过start()函数来实现调用的。
下面是我学习时的例子:
工程文件:
界面效果:
运行效果:
下面贴出代码,大家参考一下:
thread.h
#ifndef THREAD_H
#define THREAD_H
#include <QString>
#include <QThread>
class Thread : public QThread
{
Q_OBJECT
public:
Thread();
void setMessage(QString message);
void stop();
protected:
void run();
void printmessage();
private:
QString messageStr;
volatile bool stopped;
};
//stopped被声明为易失性变量(volatile variable,断电或中断时数据丢失而不可再恢复的变量类型),
//这是因为不同的线程都需要访问它,并且我们也希望确保它能在任何需要的时候都保持最新读取的数值。如果省略关键字volatile,
//则编译器就会对这个变量的访问进行优化,可能导致不正确的结果。
#endif // THREAD_H
thread.cpp
#include "thread.h"
#include <QDebug>
Thread::Thread()
{
stopped = false;
}
void Thread::run()
{
while(!stopped)
{
printmessage();
}
stopped =false;
}
void Thread::stop()
{
stopped = true;
}
void Thread::setMessage(QString message)
{
messageStr = message;
}
void Thread::printmessage()
{
qDebug() << messageStr;
sleep(1);
}
threadDialog.h
#ifndef THREADDIALOG_H
#define THREADDIALOG_H
#include <QDialog>
#include "thread.h"
#include <QCloseEvent>
namespace Ui {
class ThreadDialog;
}
class ThreadDialog : public QDialog
{
Q_OBJECT
public:
explicit ThreadDialog(QWidget *parent = 0);
~ThreadDialog();
protected:
void closeEvent(QCloseEvent *event);
private slots:
void on_ApushButton_clicked();
void on_BpushButton_clicked();
void on_QuitpushButton_clicked();
private:
Ui::ThreadDialog *ui;
Thread threadA;
Thread threadB;
};
#endif // THREADDIALOG_H
threadDialog.cpp
#include "threaddialog.h"
#include "ui_threaddialog.h"
ThreadDialog::ThreadDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::ThreadDialog)
{
ui->setupUi(this);
threadA.setMessage("A");
threadB.setMessage("B");
}
ThreadDialog::~ThreadDialog()
{
delete ui;
}
void ThreadDialog::on_ApushButton_clicked()
{
if(threadA.isRunning())
{
this->ui->ApushButton->setText("stop A");
threadA.stop();
this->ui->ApushButton->setText("start A");
}
else
{
this->ui->ApushButton->setText("start A");
threadA.start();
this->ui->ApushButton->setText("stop A");
}
}
void ThreadDialog::on_BpushButton_clicked()
{
if(threadB.isRunning())
{
this->ui->BpushButton->setText("stop B");
threadB.stop();
this->ui->BpushButton->setText("start B");
}
else
{
this->ui->BpushButton->setText("start B");
threadB.start();
this->ui->BpushButton->setText("stop B");
}
}
void ThreadDialog::on_QuitpushButton_clicked()
{
this->close();
// exit(0);
}
void ThreadDialog::closeEvent(QCloseEvent *event)
{
threadA.stop();
threadB.stop();
threadA.wait();
threadB.wait();
event->accept();
}
main.cpp
#include "threaddialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ThreadDialog w;
w.show();
w.exec();
return a.exec();
}