Qt线程停止了UI的响应 [英] Qt threading stopped UI from responding

查看:364
本文介绍了Qt线程停止了UI的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我可能会误解Qt线程中的几个概念,

I think I might misunderstood several concepts in Qt's threading,

在我的窗口类中,它是从QWidget派生的:

In my window class, which is derived from QWidget:

class Widget 
{
   Q_OBJECT
public:
   Widget::Widget (QObject *parent = 0) : QObject(parent)
   {
     moveToThread(&th); // still stuck
     connect (&th, SIGNAL(started()), SLOT(doWork())); 
     th.start();
   }
private:
   QThread th;
private slots:
  void doWork () 
  { 
     // hmm, this stuck the UI
     while (1) 
     { 
       qDebug() << "Sleeping"; 
     } 
  };
};

永远的循环卡住了UI,不应该这样,因为那是由QThread调用的. 谁能指出这段代码有什么问题吗?

The forever loop stuck the UI, it shouldn't be, since that was called by the QThread. Can anyone point out what's wrong about this code?

推荐答案

Widget::dowork()在主线程(运行GUI的主线程)上执行,因此被阻止.没关系,它是由QThread调用的.

Widget::dowork() is executed on the main thread (on which the GUI runs), that's why it blocks. It doesn't matter that it was called by a QThread.

在另一个线程上执行代码的正确方法是,首先使用QObject::moveToThread()将QObject实例移至QThread,然后将QThread的started()信号连接至要执行的QObject实例的插槽.

The correct way to execute code on another thread is to first move a QObject instance to a QThread using QObject::moveToThread(), and then connect the started() signal of the QThread to the slot of the QObject instance that you want executed.

如果您想了解更多信息: http: //blog.qt.digia.com/2010/06/17/youre-doing-it-wrong/

If you want to know more: http://blog.qt.digia.com/2010/06/17/youre-doing-it-wrong/

代码的另一个问题是,您试图将QWidget派生的对象移动到另一个线程.这是不允许的. QWidget实例必须保留在主线程上.相反,您应该从QObject继承子类.

Another issue with your code is that you're trying to move a QWidget-derived object to another thread. This is not allowed. QWidget instances must remain on the main thread. Instead, you should subclass from QObject.

代码的另一个问题是您正在构造函数中执行此操作.在对象尚未完全构造好时将其移动到另一个线程只是在自找麻烦.

Yet another issue with the code is that you're doing this in the constructor. Moving the object to another thread while it's not fully constructed yet is just asking for trouble.

这篇关于Qt线程停止了UI的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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