码迷,mamicode.com
首页 > 编程语言 > 详细

Qt 多线程使用moveToThread

时间:2019-05-06 11:46:06      阅读:290      评论:0      收藏:0      [点我收藏+]

标签:char   两种   col   转移   object   RKE   quit   win   space   

Qt有两种多线程的方法,其中一种是继承QThread的run函数,
另外一种是把一个继承于QObject的类用moveToThread函数转移到一个Thread里。 
Qt4.8之前都是使用继承QThread的run这种方法,但是Qt4.8之后,Qt官方建议使用第二种方法。

//tes.h
#ifndef TES_H
#define TES_H

#include <QCoreApplication>
#include <QDebug>
#include <QThread>
#include <QString>
#include <QObject>

class Worker:public QObject
{
    Q_OBJECT
public:
    explicit Worker(QObject *parent=0);
    ~Worker();

signals:
    void sig_finish();

public slots:
    void slot_dowork();

};


#endif // TES_H
//tes.cpp
#include "tes.h"

Worker::Worker(QObject *parent):QObject(parent)
{
    qDebug()<<"worker()";
}
Worker::~Worker()
{
    qDebug()<<"~worker()";
}
void Worker::slot_dowork()
{
    qDebug()<< "do work,thread id = " << QThread::currentThreadId();
    emit sig_finish();
}
//mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "tes.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void dowork();

private:
    Ui::MainWindow *ui;
    Worker *m_pworker;
    QThread *m_pthread;

signals:
    void sig_dowork();

public slots:
    void slot_finish();
};

#endif // MAINWINDOW_H
//mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    qDebug()<<"mainwindow()";
    ui->setupUi(this);

    m_pworker = new Worker();
    m_pthread = new QThread();
    m_pworker->moveToThread(m_pthread);
    qDebug()<< "start,thread id = " << QThread::currentThreadId();

    connect(m_pthread, &QThread::finished, m_pworker, &QObject::deleteLater);
    connect(this,SIGNAL(sig_dowork()),m_pworker,SLOT(slot_dowork()));
    connect(m_pworker,SIGNAL(sig_finish()),this,SLOT(slot_finish()));
}

MainWindow::~MainWindow()
{
    qDebug()<<"~mainwindow()";
    delete ui;
    m_pthread->quit();
    m_pthread->wait();
}

void MainWindow::dowork()
{
    m_pthread->start();
    emit sig_dowork();
}

void MainWindow::slot_finish()
{
     qDebug()<< "finish,thread id = " << QThread::currentThreadId();
}
//main.cpp
#include <QCoreApplication>
#include <QDebug>
#include <QThread>
#include <QString>
#include <QObject>
#include <QApplication>
#include "tes.h"
#include "mainwindow.h"

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

     MainWindow w;
     w.show();
     w.dowork();

    return a.exec();
}

 

Qt 多线程使用moveToThread

标签:char   两种   col   转移   object   RKE   quit   win   space   

原文地址:https://www.cnblogs.com/nanqiang/p/10818609.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!