Qt Run Slot In Another Thread

Posted on by admin

The QtConcurrent::run() function runs a function in a separate thread. The return value of the function is made available through the QFuture API.

The QThreadclass provides a platform-independent way to manage threads. A QThreadobject 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. Qt provides the signals and slots framework which allows you to do just that and is thread-safe, allowing safe communication directly from running threads to your GUI frontend. Signals allow you to.emit values, which are then picked up elsewhere in your code by slot functions which have been linked with.connect. Creating a class and moving it to a thread in a different QThread prevents QWebChannel's queued interaction. To Reproduce: Implement a new class which contains at least 1 public slot (void return) Create an instance of custom class derived from QObject myClass; Create an instance of QThread myClassThread. The QtConcurrent::run function runs a function in a separate thread. The return value of the function is made available through the QFuture API. This function is a part of the Qt Concurrent framework. Running a Function in a Separate Thread. To run a function in another thread, use QtConcurrent::run. Very easy, and wil run each function in a pool thread, Look for QtConcurrent in dicumentation.

This function is a part of the Qt Concurrent framework.

Running a Function in a Separate Thread

To run a function in another thread, use QtConcurrent::run():

This will run aFunction in a separate thread obtained from the default QThreadPool. You can use the QFuture and QFutureWatcher classes to monitor the status of the function.

To use a dedicated thread pool, you can pass the QThreadPool as the first argument:

Passing Arguments to the Function

Passing arguments to the function is done by adding them to the QtConcurrent::run() call immediately after the function name. For example:

Qt run slot in another thread pattern

A copy of each argument is made at the point where QtConcurrent::run() is called, and these values are passed to the thread when it begins executing the function. Changes made to the arguments after calling QtConcurrent::run() are not visible to the thread.

Returning Values from the Function

Any return value from the function is available via QFuture:

As documented above, passing arguments is done like this:

Note that the QFuture::result() function blocks and waits for the result to become available. Use QFutureWatcher to get notification when the function has finished execution and the result is available.

Additional API Features

Using Member Functions

Qt Run Slot In Another Thread

QtConcurrent::run() also accepts pointers to member functions. The first argument must be either a const reference or a pointer to an instance of the class. Passing by const reference is useful when calling const member functions; passing by pointer is useful for calling non-const member functions that modify the instance.

For example, calling QByteArray::split() (a const member function) in a separate thread is done like this:

Calling a non-const member function is done like this:

Using Lambda Functions

Qt Run Slot In Another Thread Set

Calling a lambda function is done like this:

Qt Run Slot In Another Thread Size

© 2020 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

This post is about the use of QThread. It is an answer to a three years old blog post by Brad, my colleague at the time:
You're doing it wrong

In his blog post,Brad explains that he saw many users misusing QThread by sub-classing it, adding someslots to that subclass and doing something like this in the constructor:

They move a thread to itself. As Brad mentions, it is wrong: the QThread is supposed tobe the interface to manage the thread. So it is supposed to be used from the creating thread.

Slots in the QThread object are then not run in that thread and having slots in a subclass of QThreadis a bad practice.

But then Brad continues and discourages any sub-classing of QThread at all.He claims it is against proper object-oriented design.This is where I disagree. Putting code in run() is a valid object-oriented way to extend a QThread:A QThread represents a thread that just starts an event loop, a subclass represents a threadthat is extended to do what's in run().

Qt Run Slot In Another Thread Pattern

After Brad's post, some members of the community went on a crusade against sub-classing QThread.The problem is that there are many perfectly valid reasons to subclass QThread.

With Qt 5.0 and Qt 4.8.4, the documentation of QThread was changed so the sample code does not involvesub-classing.Look at the first code sampleof the Qt 4.8 QThread documentation (Update: link to archive.org since the newer documentation is fixed).It has many lines of boiler plate just to run some code in a thread. And the there is evena leak: the QThread is never going to quit and be destroyed.

I was asked on IRC a question from an user who followed that example in orderto run some simple code in a thread. He had a hard time to figure out how to properlydestroy the thread. That is what motivated me to write this blog entry.

If you allow to subclass QThread, this is what you got:

This code does no longer leak and is much simpler and has lessoverhead as it does not create useless object.

The Qt threading examplethreadedfortuneserveris an example that uses this pattern to run blocking operations and is much simpler thanthe equivalent using a worker object.

I have submitted a patch to the documentationto not discourage sub-classing QThread anymore.

Rules of thumbs

Qt Run Slot In Another Threaded

When to subclass and when not to?

  • If you do not really need an event loop in the thread, you should subclass.
  • If you need an event loop and handle signals and slots within the thread, you may not need to subclass.

What about using QtConcurrent instead?

QThread is a quite low level and you should better use a higher levelAPI such as QtConcurrent.

Now, QtConcurrent has its own set of problems: It is tied to a single thread pool so it is nota good solution if you want to run blocking operations. It has also some problems in itsimplementation that gives some performance overhead. All of this is fixable.Perhaps even Qt 5.1 will see some improvements.

A good alternative is also the C++11 standard library withstd::threadand std::async which arenow the standard way to run code in a thread. And the good news is that it still works fine with Qt:All other Qt threading primitives can be used with native threads.(Qt will create automatically create a QThread if required).