qt创建线程总结

一、创建一个长时间运行的QT线程

#ifndef MYPRINTJOB_H
#define MYPRINTJOB_H

#include <QObject>
#include <QThread>

#include "MyOperation/myslicefile.h"

class MyPrintJob : public QObject
{
    Q_OBJECT
public:
    explicit MyPrintJob(QObject *parent = nullptr);
    ~MyPrintJob();

public slots:
    void StartPrintWorkSlot();

private:
    QThread *m_printJobThread;
};

#endif // MYPRINTJOB_H

然后cpp文件

#include "myprintjob.h"

MyPrintJob::MyPrintJob(QObject *parent) : QObject(parent)
{
    m_printJobThread = new QThread();
    connect(m_printJobThread, &QThread::started, this, &MyPrintJob::StartPrintWorkSlot);

    this->moveToThread(m_printJobThread);
    m_printJobThread->start();
}

MyPrintJob::~MyPrintJob()
{
    if(m_printJobThread->isRunning()) {
        m_printJobThread->quit();
        m_printJobThread->wait();
    }
}

void MyPrintJob::StartPrintWorkSlot()
{

}

 

二、创建一种可以停止的线程

#ifndef THREADTEST_H
#define THREADTEST_H

#include <QObject>
#include <QThread>
#include <QDebug>
#include <QTimer>


class ThreadTest : public QObject
{
    Q_OBJECT
public:
    explicit ThreadTest(QObject *parent = nullptr);
    ~ThreadTest();

signals:
    void workFinished();
public slots:
    void doWork();
private:
    QThread *thread;

};

#endif // THREADTEST_H

cpp文件:

#include "threadtest.h"

ThreadTest::ThreadTest(QObject *parent) : QObject(parent)
{
    thread = new QThread();
    connect(thread, &QThread::started, this, &ThreadTest::doWork);
    connect(this, &ThreadTest::workFinished, thread, &QThread::quit);
    connect(thread, &QThread::finished, this, &ThreadTest::deleteLater);
    connect(thread, &QThread::finished, thread, &QThread::deleteLater);
    this->moveToThread(thread);
    thread->start();
}

ThreadTest::~ThreadTest()
{
    qDebug()<<"~ThreadTest()";
}

void ThreadTest::doWork()
{
    qDebug()<<"doWork()";
    QTimer::singleShot(5000, this, [=](){
        emit(workFinished());
    });

}

 

posted @ 2019-12-26 09:17  习惯就好233  阅读(426)  评论(0编辑  收藏  举报