转载于https://blog.csdn.net/u014492513/article/details/52275315
项目名称:threaddlg
其中包含的文件:
threaddlg.pro
threaddlg.h
threaddlg.cpp
main.cpp
workthread.h
workthread.cpp
threaddlg.ui
导入项目的时候导入.pro文件,头文件中.h文件中存放类,变量,和方法声明。界面文件threaddlg.ui是threaddlg类的界面实现,源文件中main文件是程序的入口,默认显示threaddlg类。
main.cpp代码如下:
- #include "threaddlg.h"
- #include <QApplication>
- int main(int argc, char *argv[])
- {
- QApplication a(argc, argv);
- ThreadDlg w;
- w.show();
- return a.exec();
- }
文件中加载界面显示的控件,变量都放在了threaddlg.h文件中.
threaddld.h源代码如下:
- #ifndef THREADDLG_H
- #define THREADDLG_H
- #include <QDialog>
- #include <QPushButton>
- #include "workthread.h"
- #define MAXSIZE 2
- namespace Ui {
- class ThreadDlg;
- }
- class ThreadDlg : public QDialog
- {
- Q_OBJECT
- public:
- explicit ThreadDlg(QWidget *parent = 0);
- ~ThreadDlg();
- private:
- Ui::ThreadDlg *ui;
- QPushButton *startBtn;
- QPushButton *stopBtn;
- QPushButton *quitBtn;
- WorkThread *workThraed[MAXSIZE];
- public slots:
- void slotStart();
- void slotStop();
- };
- #endif // THREADDLG_H
- #include "threaddlg.h"
- #include "ui_threaddlg.h"
- #include <QHBoxLayout>
- #include <QDebug>
- ThreadDlg::ThreadDlg(QWidget *parent) :
- QDialog(parent),
- ui(new Ui::ThreadDlg)
- {
- ui->setupUi(this);
- setWindowTitle(tr("线程"));
- startBtn=new QPushButton(tr("开始"));
- stopBtn=new QPushButton(tr("停止"));
- quitBtn=new QPushButton(tr("退出"));
- QHBoxLayout *mainLayout=new QHBoxLayout(this);
- mainLayout->addWidget(startBtn);
- mainLayout->addWidget(stopBtn);
- mainLayout->addWidget(quitBtn);
- connect(startBtn,SIGNAL(clicked()),this,SLOT(slotStart()));
- connect(stopBtn,SIGNAL(clicked()),this,SLOT(slotStop()));
- connect(quitBtn,SIGNAL(clicked()),this,SLOT(close()));
- }
- void ThreadDlg::slotStart()
- {
- for(int i=0;i<MAXSIZE;i++)
- {
- workThraed[i]=new WorkThread();
- }
- for(int i=0;i<MAXSIZE;i++)
- {
- workThraed[i]->start();
- }
- startBtn->setEnabled(false);
- stopBtn->setEnabled(true);
- }
- void ThreadDlg::slotStop()
- {
- for(int i=0;i<MAXSIZE;i++)
- {
- workThraed[i]->terminate();
- workThraed[i]->wait();
- }
- startBtn->setEnabled(true);
- stopBtn->setEnabled(false);
- }
- ThreadDlg::~ThreadDlg()
- {
- delete ui;
- }
还是一样先建立一个头文件用来放多线程任务中需要的变量和方法的,头文件workthread.h的源代码如下:
- #ifndef WORKTHREAD_H
- #define WORKTHREAD_H
- #include <QThread>
- class WorkThread : public QThread
- {
- Q_OBJECT
- public:
- WorkThread();
- protected:
- void run();
- };
- #endif // WORKTHREAD_H
方法定义好了之后,在cpp文件中实现方法。workthred.CPP文件的源代码如下:
- #include "workthread.h"
- #include <QtDebug>
- WorkThread::WorkThread()
- {
- }
- void WorkThread::run()
- {
- while(true)
- {
- for(int n=0;n<10;n++)
- qDebug()<<n<<n<<n<<n<<n<<n;
- }
- }