/*************************方法一:run()*********************/
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QDebug>
class MyThread : public QThread
{
public:
explicit MyThread(){}
private:
void run() override;
private slots:
void sig_ShowMsg(QString,bool);
#endif // MYTHREAD_H
void MyThread::run()
{
//复杂函数的执行
emit sig_ShowMsg("发送成功",true);
}
/***************mainwindow.h**************/
//定义线程
MyThread* m_thread;
signals:
void slt_ShowMsg(QString ,bool );
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//声明线程
m_thread = new MyThread;
//二者之间通过信号与槽联系
connect(&m_thread,SIGNAL(sig_ShowMsg(QString,bool)),SLOT(slt_ShowMsg(QString ,bool )));
}
//通过按钮触发线程开启
void MainWindow::on_btnstart_clicked()
{
thread->start();//使用该函数的时候会自动调用run函数
qDebug()<<"main thread: "<< QThread::currentThreadId();
emit sig_start();
}
//通过按钮停止线程
void MainWindow::on_btnclose_clicked()
{
//结束线程
thread->exit();
thread->deleteLater();
emit sig_Close();
}
void MainWindoe::slt_ShowMsg(QString a,bool b)
{
ui->text->setText(a);
}
/******************************************方法二:movetoThread()**************/
//线程处理对象
#ifndef MYOBJECT_H
#define MYOBJECT_H
#include <QObject>
#include <QThread>
#include <QDebug>
class MyObject : public QObject
{
Q_OBJECT
public:
explicit MyObject(QObject *parent = 0): QObject(parent){}
~MyObject(){}
private slots:
void Start()//线程处理函数
{
qDebug()<<"obj thread: "<<QThread::currentThreadId();
}
};
//定义变量
MyObject* obj;
QThread* thread;
//开始线程
obj = new MyObject;//线程执行对象
thread = new QThread;
obj->moveToThread(thread);//将对象移动到新建立的线程
connect(thread, &QThread::started, obj, &MyObject::Start);//绑定线程的开始信号,线程开始后就会执行obj的Start槽函数
thread->start();
qDebug()<<"main thread: "<<QThread::currentThreadId();
//结束线程
thread->exit();
thread->deleteLater();//删除对象
obj->deleteLater();
#endif // MYOBJECT_H