QThread :: finished()永远不会发出? [英] QThread::finished() is never emitted?

查看:733
本文介绍了QThread :: finished()永远不会发出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有永远循环喜欢这个问题,但仍然不会发出finish()信号,

I don't have a forever loop like this question, but it still doesn't emit the finished() signal,

在类的构造函数中:

connect (&thread, SIGNAL(started()), SLOT(threadFunc()));
connect (&thread, SIGNAL(finished()), SLOT(finished()));

在finish()函数中,

In the finished() function,

void XX::finished()
{
  qDebug() << "Completed";
}

void XX::threadFunc()
{
  qDebug() << "Thread finished"; // only single line, finishes immediately
}

但是我从没见过finished()被调用,每次在用thread.start()启动线程之前,我都必须手动调用thread.terminate(),我是否误解了QThread的用法?

But I never see the finished() get called, everytime before I start the thread with thread.start(), I must call thread.terminate() manually, did I misunderstood the usage of QThread?

推荐答案

QThread将在QThread::run方法完成时发出finished信号.也许,您对此有错误的实现.

QThread will emit finished signal when QThread::run method is finished. Perhaps, you have incorrect implementation of this.

run方法的默认实现如下所示.它只是调用另一个exec方法.

Default implementation of run method looks like this. It just calls another exec method.

void QThread::run()
{
    (void) exec();
}

exec方法的实现稍微复杂一些.现在我简化了.

Implementation of exec method is a bit more complex. Now I simplified it.

int QThread::exec()
{
    // .....

    if (d->exited) {
        return d->returnCode;   
    }

    // ......

    QEventLoop eventLoop;
    int returnCode = eventLoop.exec();
    return returnCode;
}

从代码来看,它可以在两种情况下完成.在第一种情况下,如果它已经退出.在第二秒,它进入事件循环并等待直到调用exit().

Judging by code, it can finish in two cases. In first case if it is already exited. In second it enters the event loop and waits until exit() is called.

现在我们怎么看,您的无限线程循环就在这里.因此,您需要QThread::quit()等于QThread::exit(0).

How we can see now, your infinity thread loop is here. So you need QThread::quit() which is equal QThread::exit(0).

PS .请勿使用terminate.很危险.

P.S. Don't use terminate. It is dangerous.

这篇关于QThread :: finished()永远不会发出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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