5

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.

Surjya Narayana Padhi
  • 7,741
  • 25
  • 81
  • 130

2 Answers2

9

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

ololuki
  • 377
  • 1
  • 7
  • 14
Patrice Bernassola
  • 14,136
  • 6
  • 46
  • 59
  • 2
    so wait, basically in the first link you provided, the author tells me NOT to subclass from QThread, and in the second link another author tells me how easy Qt threads are if i subclass QThread. I'm a bit confused now, but thanks for the links anyway ;) +1 – Hafnernuss Feb 20 '13 at 07:47
  • Not exactly. First article explains why QThread should not be inherited in this case and the second explain how to use the QThread class without subclassing it – Patrice Bernassola Feb 20 '13 at 08:26
  • sorry, i noticed that. guess it was too early for me. thanks for clearification ;) – Hafnernuss Feb 20 '13 at 12:02
  • 1
    the links are damage. – H.Ghassami Apr 09 '16 at 04:37
3

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.

Cătălin Pitiș
  • 14,123
  • 2
  • 39
  • 62