在Qt中使用多线程要在类中继承QThread类:
#ifndef _THREAD_H_
#define _THREAD_H_
#include <QThread>
#include <QString>
class Thread:public QThread
{
public:
Thread();
void setMessage(const QString &message);
void run();
void stop();
private:
QString messageStr;
volatile bool stopped;
};
#endif
下面是线程类的实现:
#include "thread.h"
#include<iostream>
using namespace std;
Thread::Thread()
{
stopped=false;
messageStr="a";
}
void Thread::run()
{
while(!stopped)
cout<<messageStr.toStdString ();
stopped=false;
cerr<<endl;
}
void Thread::stop()
{
stopped=true;
}
void Thread::setMessage(const QString &message)
{
messageStr=message;
}
UI界面的设计类:
#ifndef _THREADFORM_H_
#define _THREADFORM_H_
#include<QtGui>
#include "thread.h"
class QPushButton;
class ThreadForm:public QDialog
{
Q_OBJECT
public:
ThreadForm(QWidget *parent=0);
protected:
void closeEvent(QCloseEvent *event);
private slots:
void startOrStopTheadA();
void startOrStopTheadB();
private:
Thread threadA;
Thread threadB;
QPushButton *threadAButton;
QPushButton *threadBButton;
QPushButton *quitButton;
};
#endif
GUI界面的实现:
#include "ui_thread.h"
ThreadForm::ThreadForm(QWidget *parent):QDialog(parent)
{
setWindowTitle(tr("Threads"));
threadA.setMessage("thread A");
threadB.setMessage("thread B");
threadAButton=new QPushButton(tr("start A"));
threadBButton=new QPushButton(tr("start B"));
quitButton=new QPushButton(tr("quit"));
QHBoxLayout *hbox=new QHBoxLayout(this);
hbox->addWidget(threadAButton);
hbox->addWidget(threadBButton);
hbox->addWidget(quitButton);
//quitButton->setDefault(true);
connect(threadAButton,SIGNAL(clicked() ),this, SLOT( startOrStopTheadA() ));
connect(threadBButton,SIGNAL(clicked() ),this, SLOT( startOrStopTheadB() ));
connect(quitButton,SIGNAL(clicked() ),this, SLOT( close() ));
}
void ThreadForm::startOrStopTheadA()
{
if(threadA.isRunning())
{
threadA.stop();
threadAButton->setText(tr("start A"));
}
else
{
threadA.start();
threadAButton->setText(tr("stop A"));
}
}
void ThreadForm::startOrStopTheadB()
{
if(threadB.isRunning())
{
threadB.stop();
threadBButton->setText(tr("start B"));
}
else
{
threadB.start();
threadBButton->setText(tr("stop B"));
}
}
void ThreadForm::closeEvent(QCloseEvent *event)
{
threadA.stop();
threadB.stop();
threadA.wait();
threadB.wait();
event->accept();
}
主函数的实现:
#include <qapplication.h>
#include <QTextCodec>
#include "ui_thread.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QTextCodec::setCodecForTr(QTextCodec::codecForName("System"));
ThreadForm threadform;
threadform.show();
return app.exec();
}
要使用线程类需要在生成的.pro文件中加入以下两句
CONFIG +=thread //告诉qmake 使用这个Qt库的线程版本
win32:CONFIG +=console //可以使程序从windows的控制台输出
然后再qmake -t vcapp 就可以生成工程文件了