1、在项目中增加mythread线程类
将object 类改为QTthread类
mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
class mythread : public QThread
{
Q_OBJECT
public:
// 设为传参构造对像
explicit mythread(QString s,QObject *parent = nullptr);
protected:
//QThread的虚函数,不能直接调用,通过start()间接调用
void run();
private:
QString str;
signals:
};
#endif // MYTHREAD_H
mythread.c
#include "mythread.h"
#include <QDebug>
mythread::mythread(QString s,QObject *parent) : QThread(parent)
{
str = s;
}
void mythread::run()
{
while (1)
{
qDebug()<<str<<endl;
sleep(1);
}
}
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#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();
//定义两个线程对像
mythread *t1, *t2;
void dealclose();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
widget.c
```c
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
//分配空间
t1 = new mythread("hello",this);
t2 = new mythread("world",this);
t1->start();//启动线程1
t2->start();//启动线程2
connect(this, &Widget::destroyed, this, &Widget::dealclose);
}
void Widget::dealclose()
{
t1->quit();
t1->wait();
t2->quit();
t2->wait();
}
Widget::~Widget()
{
delete ui;
}
运行结果