何时或如何在 Qt 中删除 QThread [英] When or how to delete QThread in Qt

查看:40
本文介绍了何时或如何在 Qt 中删除 QThread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从此处找到了这个 QThread 示例.推荐使用 QObject 和 QThread,而不是继承 QThread.

I found this QThread example from here. It recommends to use QObject and QThread over than subclassing QThread.

class Worker : public QObject
{
   Q_OBJECT

public slots:
    void doWork() {
        /* ... */
    }
};

QThread *thread = new QThread;
Worker *worker = new Worker;
worker->moveToThread(thread);
thread->start();
QMetaObject::invokeMethod(worker, "doWork", Qt::QueuedConnection);

我的第一个问题是何时以及如何删除该线程?

My first question is when and how to delete the thread?

我尝试将完成连接到 2 个插槽,myTest 和 deleteLater.我在 myTest 中设置了一个断点,这从未被触发.所以我怀疑没有完成信号,这意味着该线程不会被删除.

I have tried to connect finished to 2 slots, myTest and deleteLater. And I set a breakpoint in myTest, this never got triggered. So I suspect there is no finished signal, which mean the thread would not be deleted.

connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), this, SLOT(myTest()));

对于工作对象,我发出一个完成信号作为 doWork 中的最后一条指令,并将其连接到一个插槽,我可以在其中删除工作对象.这是正确的方法吗?

For the worker object, I emit a finished signal as the last instruction in doWork, and connect it to a slot in which I can delete the worker object. Is this the right way?

Qt 版本:4.6.2

Qt version: 4.6.2

推荐答案

你的线程在 worker 方法执行完成后正常退出,但是如果你想在线程退出时做一些事情,使用finished() 信号并且可以通过将 finished() 信号连接到 QObject::deleteLater():

Your thread exits normally when its worker method execution completed, but if you want to do some things in thread exit time, use the finished() signal and it is possible to deallocate objects that live in thread that has just ended, by connecting the finished() signal to QObject::deleteLater():

connect(workerThread, &WorkerThread::finished, workerThread, &QObject::deleteLater);

这篇关于何时或如何在 Qt 中删除 QThread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆