Qt多线程使用

1、MyWidget

#ifndef MYWIDGET_H
#define MYWIDGET_H

#include <QWidget>

class MyWidget : public QWidget
{
    Q_OBJECT
public:
    explicit MyWidget(QWidget *parent = 0);

signals:

public slots:
    void slotThreadQuit();
};

#endif // MYWIDGET_H

2、Mywidget.cpp

#include "MyWidget.h"
#include <QPushButton>
#include "Worker.h"
#include <QHBoxLayout>
#include <QDebug>

MyWidget::MyWidget(QWidget *parent) :
    QWidget(parent)
{
    QHBoxLayout* lay = new QHBoxLayout(this);

    Worker* work = new Worker;
    QPushButton* button = new QPushButton("StarWork",this);
    connect(button,SIGNAL(clicked()),work,SLOT(slotDoJob()));
    lay->addWidget(button);

    button = new QPushButton("StopWork",this);
    //线程退出
    connect(button,SIGNAL(clicked()),work->_thread,SLOT(quit()));
    lay->addWidget(button);

    connect(work->_thread,SIGNAL(finished()),this,SLOT(slotThreadQuit()));

}

void MyWidget::slotThreadQuit()
{
    qDebug()<<"slotThreadQuit is called";
}

3、Worker.h

#ifndef WORKER_H
#define WORKER_H

#include <QObject>
#include <QThread>

//繁重的工作
class Worker : public QObject
{
    Q_OBJECT
public:
    explicit Worker(QObject *parent = 0);

    QThread* _thread;

signals:

public slots:
    void slotDoJob();

};

#endif // WORKER_H

4、Worker.cpp

#include "Worker.h"
#include <QThread>
#include <QDebug>
#include <QMessageBox>

/*某个对象属于线程,线程托管*/
Worker::Worker(QObject *parent) :
    QObject(parent)
{
    _thread = new QThread;
    //该对象被_thread接管
    this->moveToThread(_thread);
    _thread->start();

    //connect(_thread,SIGNAL(started()),);
    //线程退出时,销毁对象线程 
    connect(_thread,SIGNAL(finished()),this,SLOT(deleteLater()));
}

void Worker::slotDoJob()
{
    //线程不支持GUI
    //QMessageBox::warning(NULL,"111","222");
    int i = 0;
    qDebug()<<"Hello slotDoJob";
#if 0
    for(;;)
    {
        ++i;
        QThread::sleep(1);
        qDebug()<< i;
    }
#endif

}

5、main.cpp
#include <QApplication>
#include "MyWidget.h"
#include <QThread>
#include <QDebug>

#if 0
class MyThread: public QThread
{
    void run()
    {
        qDebug() << "child Thread id:" << QThread::currentThreadId();
        QThread::sleep(4);
        QThread::msleep(1000);
    }
};
#endif

//1、线程不能使用GUI

int main(int argc,char* argv[])
{
    QApplication app(argc,argv);

    MyWidget w;
    w.show();

#if 0
    MyThread thread;
    QObject::connect(&thread,SIGNAL(finished()),&w,SLOT(close()));
    thread.start();
#endif

    qDebug() << "main thread id:"<< QThread::currentThreadId();

    return app.exec();
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值