QT自定义线程创建(图解+源码)
·

ui设计师显示
// mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QObject>
class Mythread : public QObject
{
Q_OBJECT
public:
explicit Mythread(QObject *parent = nullptr);
void MyTimer(); // 有效函数
bool isAction; // 用于控制有效函数MyTimer的进行
signals:
void Mysignal(); // 连接有效函数(槽)与 主程序的处理函数
public slots:
};
#endif // MYTHREAD_H
// mythread.cpp
#include "mythread.h"
#include <QThread>
#include <QDebug>
#define cout qDebug()
Mythread::Mythread(QObject *parent) : QObject(parent)
{
isAction = true;
}
void Mythread::MyTimer(){
while (isAction) {
QThread::sleep(1); // 睡眠1s
emit Mysignal(); // 触发信号,穿给主程序的处理函数deelsignal
}
//mythreadwidget.h
#ifndef MYTHREADWIDGET_H
#define MYTHREADWIDGET_H
#include <QWidget>
#include<QThread>
#include"mythread.h"
namespace Ui {
class myThreadWidget;
}
class myThreadWidget : public QWidget
{
Q_OBJECT
public:
explicit myThreadWidget(QWidget *parent = nullptr);
~myThreadWidget();
private slots:
void on_but_start_clicked();
void deelsignal(); // 最终处理函数
void on_but_stop_clicked();
signals:
void startThread(); // 线程启动信号
private:
Ui::myThreadWidget *ui;
QThread *thread;
Mythread * me;
};
#endif // MYTHREADWIDGET_H
//mythreadwidget.cpp
#include "mythreadwidget.h"
#include "ui_mythreadwidget.h"
#include<QDebug>
#define cout qDebug()
myThreadWidget::myThreadWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::myThreadWidget)
{
ui->setupUi(this);
thread = new QThread(this);
me = new Mythread; // 不可以指定this,否则将于主线程共同进行
me->moveToThread(thread); // 将自定义线程加入线程
connect(me, &Mythread::Mysignal, this, &myThreadWidget::deelsignal);
connect(this, &myThreadWidget::startThread, me, &Mythread::MyTimer);
// 通过信号starThread->触发MyTimer(槽)->触发Mysignal(信号)->触发deelsignal(使LCD启动计数)
connect(this, &myThreadWidget::destroyed, [=](){ // 关闭时结束线程
me->isAction = false;
thread->quit();
//cout<<"关闭"<<endl;
});
}
void myThreadWidget::deelsignal(){ // 信号传输的最终处理
static int i = 0;
++i;
ui->lcdNumber->display(i); // 设置LCD显示
}
myThreadWidget::~myThreadWidget()
{
delete ui;
}
void myThreadWidget::on_but_start_clicked()
{
if(me->isAction) return;
me->isAction = true; // 使自定义线程运行函数MyTimer 进入循环
thread->start(); // 启动线程,但是并不运行有效函数
emit startThread(); // 点击触发信号startThread,用于启发槽MyTimer
}
void myThreadWidget::on_but_stop_clicked()
{
if(!me->isAction) return;
me->isAction = false; // 将自定义程序运行函数MyTimer 可以退出循环
thread->quit(); // 关闭线程
}
更多推荐


所有评论(0)