且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Qthread-Qt5 创建新线程

更新时间:2023-11-14 14:23:22

从 QThread 继承不是推荐的用法.QThread 是一个运行事件循环的完整类,这通常是您需要的.文档 建议使用从 QObject 继承的工作对象并在一个插槽.工作线程被移动到 QThread 中.当发送连接信号时,槽将运行在正确的线程中.

Inheriting from QThread is not the recommended usage. QThread is a complete class that runs an event loop, which is generally what you need. The documentation recommends using a worker object that inherits from QObject and does work in a slot. The worker is moved into a QThread. When a connected signal is sent, the slot will run in the correct thread.

class gpsworker: public QObject
{
Q_OBJECT
public:
    explicit gpsworker(QObject *parent = 0):
    QObject(parent)
    {}

public slots:
    void processgps() {
        qDebug() << "processgps()" << QThread::currentThreadId();
    }
}

void OwnerClass::startWorker() {
    QTimer *timer = new QTimer(this);
    QThread *thread = new QThread(this);
    this->worker = new gpsworker();
    this->worker->moveToThread(thread);
    connect(timer, SIGNAL(timeout()), this->worker, SLOT(processgps()) );
    connect(thread, SIGNAL(finished()), this->worker, SLOT(deleteLater()) );
    thread->start();
    timer->start();
}

如果你想让定时器也存在于另一个线程中,QTimer::start 是一个槽.

If you want the timer to live in the other thread as well, QTimer::start is a slot.