Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 878
Surjya Narayana Padhi Avatar asked Dec 22 '10 06:12

Surjya Narayana Padhi


People also ask

How do you run a function in QThread?

There are two main ways of running code in a separate thread using QThread: subclassing QThread and overriding run(); creating a “worker object” (some QObject subclass) and connecting it to QThread signals.

Is Qt multithreaded?

Qt makes it easy to write multithreaded applications. Signals and slots can be used to safely communicate between threads in your application. The QtConcurrent namespace includes a collection of classes and functions for straightforward concurrent programming.

What is QFuture?

QFuture provides a Java-style iterator (QFutureIterator) and an STL-style iterator (QFuture::const_iterator). Using these iterators is another way to access results in the future. QFuture also offers ways to interact with a running computation. For instance, the computation can be canceled with the cancel() function.

What is a QThread?

A QThread object manages one thread of control within the program. QThreads begin executing in run(). By default, run() starts the event loop by calling exec() and runs a Qt event loop inside the thread. You can use worker objects by moving them to the thread using QObject::moveToThread().


1 Answers

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

like image 122
Patrice Bernassola Avatar answered Sep 18 '22 05:09

Patrice Bernassola