1024程序员快乐,如果这博客让你学习到了知识,请给我一个免费的赞❤️
一、创建界面文件
LCDnumber
二、创建mythread类,继承QObject
三、在MyThread.h文件做修改,并且加上函数声明
引入头文件,改变继承
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = 0);
protected:
void run(); // 入口函数 -- 需要start()启动
signals:
void sigDone();
public slots:
};
#endif // MYTHREAD_H
四、实现run方法
#include "mythread.h"
MyThread::MyThread(QObject *parent) : QThread(parent)
{
}
void MyThread::run()
{
// 模拟复杂的操作
sleep(5); //休眠5s
emit sigDone();
}
五、使用计时器来控制LCDnumber
//计时器
mytimer = new QTimer(this);
myt = new MyThread(this);
connect(mytimer, &QTimer::timeout, this, [=](){
static int num = 0;
ui->lcdNumber->display(num++);
});
六、实现按钮的槽函数
void MyWidget::on_begin_clicked()
{
//如果计时器开着
if(mytimer->isActive() == true)
{
return;
}
// 启动定时器
mytimer->start(1000); // ms
// 启动子线程
myt->start();
}
子线程运行结束后,停止计数器
// 子线程信号,子线程运行结束停止计数器
connect(myt, &MyThread::finished, mytimer, &QTimer::stop);
完整代码
mythread.cpp
#include "mythread.h"
MyThread::MyThread(QObject *parent) : QThread(parent)
{
}
void MyThread::run()
{
// 模拟复杂的操作
sleep(5); //休眠5s
emit sigDone();
}
mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = 0);
protected:
void run(); // 入口函数 -- 需要start()启动
signals:
void sigDone();
public slots:
};
#endif // MYTHREAD_H
mywidget.cpp
#include "mywidget.h"
#include "ui_mywidget.h"
#include <QThread>
#include <QDebug>
MyWidget::MyWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::MyWidget)
{
ui->setupUi(this);
//计时器
mytimer = new QTimer(this);
myt = new MyThread(this);
connect(mytimer, &QTimer::timeout, this, [=](){
static int num = 0;
ui->lcdNumber->display(num++);
});
// 子线程信号,子线程运行结束停止计数器
connect(myt, &MyThread::finished, mytimer, &QTimer::stop);
}
MyWidget::~MyWidget()
{
delete ui;
}
void MyWidget::on_begin_clicked()
{
//如果计时器开着
if(mytimer->isActive() == true)
{
return;
}
// 启动定时器
mytimer->start(1000); // ms
// 启动子线程
myt->start();
}
mywidget.h
#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
#include <QTimer>
#include "mythread.h"
namespace Ui {
class MyWidget;
}
class MyWidget : public QWidget
{
Q_OBJECT
public:
explicit MyWidget(QWidget *parent = 0);
~MyWidget();
private slots:
void on_begin_clicked();
private:
Ui::MyWidget *ui;
QTimer* mytimer;
MyThread *myt;
};
#endif // MYWIDGET_H