Qt-线程1-Run
0. 写在前面
一个应用程序一般只有一个线程,一个线程内的操作是顺序执行的,如果有某个比较耗时间的计算或操作,比如图像处理大数据图像、网络通信中的文件传输;在一个线程内操作时,用户界面就能冻结而不能及时响应。这种情况下,可以创建一个单独的线程来执行比较消耗时间的操作,并与主线程之间处理好同步与数据交互,这时候就是多线程的应用程序了。
1. 利用QThread类,创建
(1)自定义一个类,继承于QThread
class MyThread:public QThread
{
public:
void run();//线程处理函数(和主函数不是同一个线程)
}
void run()
{
QThread::sleep(5);
emit isDone();
}
在Qt文件中新添加MyThread类,基类选择QObject,随后修改三处地方:
(1)将#include<QObject>修改为#include<QThread>;
(2)将MyThread类中,class MyThread : public QObject修改为class MyThread : public QThread;
(3)将MyThread.cpp函数中,MyThread::MyThread(QObject *parent) : QObject(parent)修改为MyThread::MyThread(QObject *parent) : QThread(parent)。
### myThread.h ###
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QTimer>
#include <QDebug>
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
### widget.h ###
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include "mythread.h"
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void on_pBtn_start_clicked();
void dealDone(); //定时器槽函数
void dealTimeout(); //现成结束槽函数
void stopThread(); //停止线程槽函数
private:
Ui::Widget *ui;
QTimer* timer1;
MyThread* thread; // 线程对象
};
#endif // WIDGET_H
### mythread.cpp ###
#include "mythread.h"
MyThread::MyThread(QObject *parent) : QThread(parent)
{
}
void MyThread::run()
{
//复杂数据处理,需要耗时5s
sleep(5);
emit isDone();
}
### widget.cpp ###
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
timer1 = new QTimer();
connect(timer1,&QTimer::timeout,this,&Widget::dealTimeout);
//分配空间
thread = new MyThread(this);
connect(thread,&MyThread::isDone,this,&Widget::dealDone);
//当按窗口右上角关闭窗口时,窗口触发destroyed
connect(this,&Widget::destroyed,this,&Widget::stopThread);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pBtn_start_clicked()
{
if(timer1->isActive() == false)
{
//启动定时器
timer1->start(100);
}
// QThread::sleep(5);
// //处理完之后,关闭定时器
// timer1->stop();
// qDebug() << "Over!";
//启动线程
thread->start();
}
void Widget::dealDone()
{
qDebug() << "It is Over!";
timer1->stop();//关闭定时器
}
void Widget::dealTimeout()
{
static int i = 0;
i++;
ui->lcdNumber->display(i);
}
void Widget::stopThread()
{
thread->quit();
thread->wait();
}
原文地址:https://blog.csdn.net/Skywalker_air/article/details/137462327
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!