Want to put a method into a QThread

血红的双手。 提交于 2019-12-21 23:20:02

问题


How to add a method within the class to a thread to execute?

I do not want to put "Pup" into a seperate class that inherits QThread as this is just an abstraction of some Legacy code I am working on.

void Dog::Pup()
{
     printf("pup");
}

void Dog::Init()
{
     QThread *dogThread = new QThread();
     Pup->moveToThread(dogThread); //this is all wrong
     Pup->connect(dogThread, ?, Pup, SLOT(Pup), ?)
     dogThread.start();
}

回答1:


Try this:

void Dog::Init()
{
     QThread *dogThread = new QThread;
     connect(dogThread, SIGNAL(started()), this, SLOT(Pup()), Qt::DirectConnection);
     dogThread->start();
}

It basically creates a new QThread named dogThread and connects it's started() signal to the method you want to run inside the thread (Dog::Pup() which must be a slot).

When you use a Qt::QueuedConnection the slot would be executed in the receiver's thread, but when you use Qt::DirectConnection the slot will be invoked immediately, and because started() is emitted from the dogThread, the slot will also be called from the dogThread. You find more information about the connection types here: Qt::ConnectionType.




回答2:


if you want to run a single function in another thread, you should check out the methods in the QtConcurrent namespace.




回答3:


Read the Detailed description in the page http://doc.qt.io/qt-5/qthread.html



来源:https://stackoverflow.com/questions/17241422/want-to-put-a-method-into-a-qthread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!