问题
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