QT的多线程基础
第一种方法:
1. 创建一个类从QThread类派生
2. 在子线程类中重写 run 函数, 将处理操作写入该函数中
3. 在主线程中创建子线程对象, 启动子线程, 调用start()函数
要求:让一个定时器在工作五秒之后,定时器停止
mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QObject>
#include <QWidget>
#include<QThread>
class mythread : public QThread
{
Q_OBJECT
public:
explicit mythread(QObject *parent = nullptr);
protected:
void run();
signals:
void is_Done();
public slots:
};
#endif // MYTHREAD_H
widget.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QObject>
#include <QWidget>
#include<QThread>
class mythread : public QThread
{
Q_OBJECT
public:
explicit mythread(QObject *parent = nullptr);
protected:
void run();
signals:
void is_Done();
public slots:
};
#endif // MYTHREAD_H
main
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
mythread.cpp
#include "mythread.h"
mythread::mythread(QObject *parent) : QThread(parent)
{
}
void mythread::run()
{
sleep(5);
emit is_Done();
}
widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
init();
}
Widget::~Widget()
{
delete ui;
}
void Widget::init()
{
mytimer=new QTimer(this);
thread1=new mythread(this);
connect( mytimer,SIGNAL(timeout()),this,SLOT(my_Lcd_slot()));
connect(ui->pushButton,SIGNAL(clicked(bool)),this,SLOT(my_Btn_slot()));
connect(thread1,SIGNAL(is_Done()),this,SLOT(my_thr_slot()));
}
void Widget::my_Lcd_slot()
{
static int x=0;
x++;
QString str= QString::number(x);
ui->lcdNumber->display(str);
}
void Widget::my_Btn_slot()
{
if( mytimer->isActive()==false)
{
mytimer->start(1000);
}
thread1->start();
}
void Widget::my_thr_slot()
{
mytimer->stop();
}
一开始运行时,程序我知道没多大问题但是就是出现这种状况,
然后瞎选
居然能运行成功了,也不知道为什么,问题先放在这里。