【原创】QT编程 多线程
请先保证已安装QT,没有请参考
http://www.cnblogs.com/kavs/p/4608926.html 安装QT。
新建threads文件夹存放项目:mkdir threads
sudo gedit main.cpp
输入如下代码:
#include <QApplication> #include "threaddialog.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); ThreadDialog dialog; dialog.show(); return app.exec(); }
保存退出文件。
终端输入
sudo gedit threa.cpp
键入代码:
#include <QtCore> #include <iostream> #include "thread.h" Thread::Thread() { stopped = false; } void Thread::setMessage(const QString &message) { messageStr = message; } void Thread::run() { while (!stopped) std::cerr << qPrintable(messageStr); stopped = false; std::cerr << std::endl; } void Thread::stop() { stopped = true; }
保存退出文件。
终端输入
sudo gedit thread.h
键入如下 代码:
#ifndef THREAD_H #define THREAD_H #include <QThread> class Thread : public QThread { Q_OBJECT public: Thread(); void setMessage(const QString &message); void stop(); protected: void run(); private: QString messageStr; volatile bool stopped; }; #endif
保存退出文件。
终端输入
sudo gedit threaddialog.cpp
键入如下代码:
#include <QtGui> #include "threaddialog.h" ThreadDialog::ThreadDialog(QWidget *parent) : QDialog(parent) { threadA.setMessage("A"); threadB.setMessage("B"); threadAButton = new QPushButton(tr("Start A")); threadBButton = new QPushButton(tr("Start B")); quitButton = new QPushButton(tr("Quit")); quitButton->setDefault(true); connect(threadAButton, SIGNAL(clicked()), this, SLOT(startOrStopThreadA())); connect(threadBButton, SIGNAL(clicked()), this, SLOT(startOrStopThreadB())); connect(quitButton, SIGNAL(clicked()), this, SLOT(close())); QHBoxLayout *mainLayout = new QHBoxLayout; mainLayout->addWidget(threadAButton); mainLayout->addWidget(threadBButton); mainLayout->addWidget(quitButton); setLayout(mainLayout); setWindowTitle(tr("Threads")); } void ThreadDialog::startOrStopThreadA() { if (threadA.isRunning()) { threadA.stop(); threadAButton->setText(tr("Start A")); } else { threadA.start(); threadAButton->setText(tr("Stop A")); } } void ThreadDialog::startOrStopThreadB() { if (threadB.isRunning()) { threadB.stop(); threadBButton->setText(tr("Start B")); } else { threadB.start(); threadBButton->setText(tr("Stop B")); } } void ThreadDialog::closeEvent(QCloseEvent *event) { threadA.stop(); threadB.stop(); threadA.wait(); threadB.wait(); event->accept(); }
保存退出文件。
终端输入
sudo threaddialog.h
键入如下代码:
#ifndef THREADDIALOG_H #define THREADDIALOG_H #include <QDialog> #include "thread.h" class QPushButton; class ThreadDialog : public QDialog { Q_OBJECT public: ThreadDialog(QWidget *parent = 0); protected: void closeEvent(QCloseEvent *event); private slots: void startOrStopThreadA(); void startOrStopThreadB(); private: Thread threadA; Thread threadB; QPushButton *threadAButton; QPushButton *threadBButton; QPushButton *quitButton; }; #endif
接下来 开始编译:
在终端进入该项目的文件夹:
开始编译 qmake –project 生成threas.pro文件
键入 qmake threads.pro 生成Makefile文件 键入make
编译程序。编译完成结果
键入./threads
over..
作者:leemoaly
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。