Surjya Narayana Padhi
Surjya Narayana Padhi

Reputation: 7841

Running a function in different thread in QT

In Qt Application code Class A has one member method like method1(). I want to call this method in another member function method2() and run mehtod1() in a different thread. But what I found from the qt documentation is follows.

  1. Inherit a new class MyThread(suppose) from QThread.
  2. Override the function method run() with your required code.
  3. Create an object of MyThread in Class A and then call the run function wherever you want.

But the above seems bit complex. Is there any mechanism in Qt so that I can create a new QThread(without inheriting) instantly in my method1() and run the method2() with this thread and then return to method1() after execution finishes?

Please let me know if I am not clear in my question.

Upvotes: 5

Views: 15039

Answers (2)

Patrice Bernassola
Patrice Bernassola

Reputation: 14446

Yes there is a way like you want.

This article will help you to understand why it's not the correct way to inherit from QThread: https://www.qt.io/blog/2010/06/17/youre-doing-it-wrong

This article will help you to know how use QThread in a real simple way: https://www.qt.io/blog/2006/12/04/threading-without-the-headache

Upvotes: 9

Cătălin Pitiș
Cătălin Pitiș

Reputation: 14317

You can use QObject slots and signals or event support, combined with threads.

Basically, a QObject's slots called through signal/slot mechanism are executed in the thread that created the QObject. You can also move the object ownership from one thread to another using QObject::moveToThread.

You can also use QCoreApplication::postEvent to post events for execution in the thread the object was created in.

See more about threads and QObjects in Qt documentation ("Threads and QObjects" topic in index).

Going to your problem, you can use two separate objects in different threads to "spread" the execution.

Upvotes: 3

Related Questions