您的位置:首页 > 编程语言 > Qt开发

Qt线程的简单使用

2015-09-09 15:55 423 查看
#include <QtWidgets/QApplication>

#include "threaddialog.h"

int main(int argc, char *argv[])

{

QApplication a(argc, argv);

ThreadDialog *threaddialog = new ThreadDialog;

threaddialog->exec();

return a.exec();

}

#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 // THREADDIALOG_H

#include "threaddialog.h"

ThreadDialog::ThreadDialog(QWidget *parent) : QDialog(parent)

{

threadA.setMessage("A");

threadB.setMessage("B");

threadAButton = new QPushButton(tr("Start A"), this);

threadAButton->setGeometry(10, 30, 80, 30);

threadBButton = new QPushButton(tr("Start B"),this);

threadBButton->setGeometry(110, 30, 80, 30);

quitButton = new QPushButton(tr("Quit"), this);

quitButton->setGeometry(210, 30, 80, 30);

quitButton->setDefault(true);

connect(threadAButton, SIGNAL(clicked()), this, SLOT(startOrStopThreadA()));

connect(threadBButton, SIGNAL(clicked()), this, SLOT(startOrStopThreadB()));

connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));

}

void ThreadDialog::startOrStopThreadA()

{

if(threadA.isRunning())

{

threadAButton->setText(tr("Stop A"));

threadA.stop();

threadAButton->setText(tr("Start A"));

}

else

{

threadAButton->setText(tr("Start A"));

threadA.start();

threadAButton->setText(tr("Stop A"));

}

}

void ThreadDialog::startOrStopThreadB()

{

if(threadB.isRunning())

{

threadBButton->setText(tr("Stop B"));

threadB.stop();

threadBButton->setText(tr("Strat B"));

}

else

{

threadBButton->setText(tr("Start B"));

threadB.start();

threadBButton->setText(tr("Stop B"));

}

}

void ThreadDialog::closeEvent(QCloseEvent *event)

{

threadA.stop();

threadB.stop();

threadA.wait();

threadB.wait();

event->accept();

}

void ThreadDialog::close()

{

exit(0);

}

#pragma once

#include <QThread>

class Thread :public QThread

{

Q_OBJECT

public:

Thread(void);

void setMessage(QString message);

void stop();

protected:

void run();

void printMessage();

private:

QString messageStr;

volatile bool stopped;

};

#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);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: