简体   繁体   English

Qt C ++ moveToThread()

[英]Qt C++ moveToThread()

I've just started working with Qt on Windows and read about moveToThread() function. 我刚刚开始在Windows上使用Qt,并了解了moveToThread()函数。 Would it be ok if I write like this: 我这样写可以吗:

class Worker : public QObject
{
    Q_OBJECT
private:
    QThread* thread;
public:
    void GoToThread() {
        thread = new QThread();
        this->moveToThread(thread);
    }
    void DoWork() {
        //long work
    }
};

Worker* w = new Worker();
w->GoToThread();
w->DoWork();

And what exactly would this code do? 这段代码到底会做什么? Would it put itself to the thread? 它会把自己放到线程上吗? Would I be able to call DoWork() outside? 我可以在外面调用DoWork()吗?

In the example you gave, DoWork() would execute on the caller's thread. 在您给出的示例中, DoWork()将在调用者的线程上执行。

If you want DoWork() to be done on the Worker object's thread, you should have DoWork() be a slot that can be invoked either by emitting a signal that it has been connected to or by calling QMetaObject::invokeMethod() to 'call' it. 如果您希望在Worker对象的线程上完成DoWork() ,则应该让DoWork()是一个插槽,可以通过发出已将其连接的信号或通过将QMetaObject::invokeMethod()调用为'称它为。

Basically, moving a Q_OBJECT to another thread makes that Q_OBJECT use an event queue associated with that thread, so any events delivered to that object via the event queue will be handled on that thread. 基本上,将Q_OBJECT移至另一个线程将使Q_OBJECT使用与该线程关联的事件队列,因此,通过该事件队列传递给该对象的任何事件都将在该线程上进行处理。

这会将QObject移至新线程,并在Michael Burr已经说过的内容之上,您应该在此处查看文档因为您至少错过了一个已完成删除操作的连接线程,以删除QObject的deleteLater(这将导致内存泄漏)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM