QThread线程

/*************************方法一: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

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值