thread.h代码
多线程
#ifndef THREAD_H
#define THREAD_H
#include <QThread>
#include <iostream>
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;
};
#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 <QPushButton>
#include <QDialog>
#include <QCloseEvent>
#include "thread.h"
class ThreadDialog : public QDialog
{
Q_OBJECT
public:
ThreadDialog(QWidget *parent=0);
protected:
void closeEvent(QCloseEvent *event);
private slots:
void startOrStopThreadA();
void startOrStopThreadB();
void close();
private:
Thread threadA;
Thread threadB;
QPushButton *threadAButton;
QPushButton *threadBButton;
QPushButton *quitButton;
};
#endif