jdl
jdl

Reputation: 6323

Want to put a method into a QThread

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

Upvotes: 1

Views: 568

Answers (3)

sky
sky

Reputation: 115

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

Upvotes: 0

Zaiborg
Zaiborg

Reputation: 2522

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

Upvotes: 0

david
david

Reputation: 633

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.

Upvotes: 4

Related Questions