1

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();
}
4

3 回答 3

3

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.

于 2013-06-21T18:31:43.567 回答
0

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

于 2013-06-21T18:18:50.937 回答
0

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

于 2013-06-21T20:46:31.927 回答