1.自定义一个类,继承于QThread,此线程不同于主函数,在主函数内不能直接调用run();
class MyThread:public QThread
{
public:
void run();//线程处理函数,
signals:
void over();
}
void run()
{
//线程操作
emit over();
}
timer.start(100);
thread.start();//间接调用run();
操作步骤;
1.新建类,命名,先选择基类QObject,后面再改
2.更改继承的基类QObject->QTread
3.查询帮助文档
4.代码如下
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include<QTimer>//
#include<mythread.h>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
void dealTimeout();//
void dealover();
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);
connect(myTimer,&QTimer::timeout,this,&Widget::dealTimeout);
thread=new MyThread(this);
connect(thread,&MyThread::over,this,&Widget::dealover);
connect(this,&Widget::destroyed,this,&Widget::stopThread);//窗口右上角关闭触发destroyed信号
}
void Widget::stopThread()
{
thread->quit();
thread->wait();
}
void Widget::dealover()
{
qDebug()<<"over";
myTimer->stop();
}
void Widget::dealTimeout()
{
static int i = 0;
i++;
//设置lcd
ui->lcdNumber->display(i);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_clicked()
{
//如果timer没有工作
if(myTimer->isActive()==false)
{
myTimer->start(100);
}
//启动线程
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:
void run();//QTread的虚函数,线程处理函数
signals:
void over();
};
#endif // MYTHREAD_H
mythread.cpp
#include "mythread.h"
MyThread::MyThread(QObject *parent) : QThread(parent)
{
}
void MyThread::run()
{
//复杂数据处理
sleep(5);
emit over();
}
6.效果图: