QT 线程中使用子线程操作注意事项

    xiaoxiao2026-05-10  1

           QT在项目使用过程中创建了一个线程,由于线程中run还是中处理有自己想要处理的业务逻辑,想在启用一个线程或者定时器去做别的事情,如果不使用信号槽的情况下使用线程是不存在问题的

    #ifndef MONITORTHREAD_H #define MONITORTHREAD_H #include <QObject> #include <QThread> #include <QDebug> #include <QTimer> class WorkerSubThread: public QThread { public: WorkerSubThread() { } virtual void run() { qDebug() << "run thread"; } }; class MonitorThread : public QThread { public: MonitorThread(); ~MonitorThread(); protected: void run(); WorkerSubThread *m_pSubThread; QTimer * m_pTimer; //public slots: // void ExecThread(); private: bool m_bStop; }; #endif // MONITORTHREAD_H

    #include "MonitorThread.h" MonitorThread::MonitorThread() { m_pSubThread = new WorkerSubThread; m_pSubThread->start(); m_pTimer = new QTimer(); connect(m_pTimer, SIGNAL(timeout()), this, SLOT(ExecThread())); m_pTimer->start(500); m_bStop = false; } MonitorThread::~MonitorThread() { m_bStop = true; } void MonitorThread::run() { while(!m_bStop) { // m_pSubThread = new WorkerSubThread; // m_pSubThread->run(); qDebug() << "run bussiness logic"; //进行相关操作 msleep(100); } } void MonitorThread::ExecThread() { if (m_pSubThread != 0) m_pSubThread->start(); } 如果使用信号槽的话需要添加Q_OBJECT宏用于此时由于将无法使用在线程中使用线程了,会报错误信息,无法连接相关的线程类。解决方法就是不使用定时器和信号槽了

    转载请注明原文地址: https://ju.6miu.com/read-1309524.html
    最新回复(0)