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()); }); }
无欲速,无见小利。欲速,则不达;见小利,则大事不成。