开一个线程:(QT4之前)
1)自定义一个类,继承于QThread
class MyThread : public QThread
{
public:
void run(); //才是线程处理函数(和主线程不在同一个线程)
signal:
void isDone(); //处理结束信号
}
void run()
{
QThread::sleep(5); //睡眠5s 解决:放在线程里面处理
emit isDone();
}
MyThread thread;
timer.start(100);
//启动线程
//不能直接调用run()
//start()间接调用run()
thread.start();
widget.h:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include<QTimer> //定时器头文件
#include "mythread.h" //包含线程头文件
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
void dealTimeout(); //定时器槽函数
void dealDone(); //线程结束槽函数
void stopThread(); //停止线程槽函数
private slots:
void on_pushButton_clicked();
private:
Ui::Widget *ui;
QTimer *myTimer; //声明变量
MyThread *thread; //线程对象
};
#endif // WIDGET_H
widget.cpp:
#include "widget.h"
#include "ui_widget.h"
#include <QThread>
#include<QDebug>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
myTimer=new QTimer(this);
//只要定时器启动 自动触发timeout()
connect(myTimer,&QTimer::timeout,this,&Widget::dealTimeout);
//分配空间
thread=new MyThread(this);
connect(thread,&MyThread::isDone,this,&Widget::dealDone);
//当按窗口右上角x时 窗口触发destroyed
connect(this,&Widget::destroyed,this,&Widget::stopThread);
}
void Widget::dealTimeout()
{
static int i=0;
i++;
//设置lcd的值
ui->lcdNumber->display(i);
}
void Widget::dealDone()
{
qDebug()<<"it is over";
myTimer->stop();
}
void Widget::stopThread()
{
//停止线程
thread->quit();
//等待线程处理完手头工作
thread->wait();
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_clicked()
{
//如果定时器没有工作
if(myTimer->isActive()==false)
{
myTimer->start(100);
}
/* //非常复杂的数据处理 耗时较长
QThread::sleep(5); //睡眠5s 解决:放在线程里面处理
//处理完数据后,关闭定时器
myTimer->stop(); //结果就是点start 不会有反应 因为是单线程 在睡眠不会工作 解决:多任务
qDebug()<<"over";*/
//启动线程 处理数据
thread->start();
}
mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = nullptr);
protected:
//QThread的虚函数
//线程处理函数
//不能直接调用 通过start()间接调用
void run();
signals:
void isDone(); //处理完了
public slots:
};
#endif // MYTHREAD_H
mythread.cpp:
#include "mythread.h"
MyThread::MyThread(QObject *parent) : QThread(parent)
{
}
void MyThread::run()
{
//很复杂的数据处理
//需要耗时5s
sleep(5);
emit isDone();
}
main.cpp:
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
widget.ui:
结果:
点start就会开始计时