【发布时间】:2013-11-07 16:40:36
【问题描述】:
我最近刚开始使用 QThreads API,遇到了一个奇怪的问题。
我用重新实现的 run() 方法创建了 QThread 的子类 这里是:
void ThreadChecker::run()
{
emit TotalDbSize(1000);
for (int i = 0; i < 1000; i++)
{
QString number;
number.setNum(i);
number.append("\n");
emit SimpleMessage(number);
//pausing is necessary, since in the real program the thread will perform quite lenghty tasks
usleep(10000);
}
}
下面是调用这个线程的代码:
ThreadChecker thread;
connect(&thread, SIGNAL(TotalDbSize(int)), this, SLOT(SetMaximumProgress(int)));
//This slot writes the message into the QTextEdit
connect(&thread, SIGNAL(SimpleMessage(QString)), this, SLOT(ProcessSimpleMessage(QString)));
thread.start();
我打算让 QTextEdit 每 10 毫秒更新一次。但相反,该程序仅滞后 10 秒,然后所有信号立即涌现。此外,当程序滞后时,它的行为就像事件循环被阻塞(按钮不会[按下,调整大小不起作用等)
我在这里错过了什么?
【问题讨论】:
-
尝试将以下内容添加到您的
ThreadCheckerctor:moveToThread(this)。但是请注意,这不是解决方案。这只是为了检查它是否有帮助,以便更好地了解您的问题。 -
如果 ctor 指的是构造函数,那么它并没有解决问题
-
你为什么不简单地使用QTimer?
-
正如cmets中所说,我使用暂停,因为在原始程序中是为了计算大块数据,通过函数有效地冻结进度
-
我只看到这种行为的一种解释。我怀疑最后一段代码在不包含事件循环执行的代码分支中,因此线程块的析构函数(调用 waitFor)你的主线程,直到你的工作完成。当您使用来自 ixSci 的代码时,您可能已经更改了该代码,并且在调用线程的析构函数之前运行事件外观。无论如何 ixScis 代码是正确的,您可能会导致一些错误。