Qt Signal Slot Call Order

This is only done in this case because almost every call to connect would generate a new different type (since the QSlotObject has template parameters wich depend on signature of the signal and the slot). Protected, Public, or Private Signals. Signals were protected in Qt4 and before. It was a design choice as signals should be emitted by the. One side note: if you are using Qt::QueuedConnection and your program looks like the following example, at some point you will probably wonder, why calling the Signal will not call the Slots until app.exec is called. The reason for this behavior is that the event queue, the Slot-call is enqueued, will start with this call (and block until.

I wrote about multi-threading in Qt a while back, and how to use QThread to wrap a blocking function call “lock free”. Today we’ll talk about how to pass data into your thread. This approach can be used, for example, to tell your QThread to stop.

There are two ways to use QThread, with and without an event loop, and the preferred method for talking to a QThread depends on which of them you use.

Way 1: Without an event loop

When you’re not using an event loop, the thread’s run() method often looks like this:

Since this method does not use an event loop, there is no way to deliver a signal to your thread. So if you want to pass data into the thread, you have to use a good old fashioned mutex. Let’s look at an example showing you how to stop your thread:

In this case, we have to check the stopRequested variable in a timely manner in our thread’s run() method. The longer you run between checks, the longer it will take your thread to actually stop.

Outside observers can use the finished() signal to know when your thread is actually done. So if you are in a QMainWindow, for example, and a closeEvent() happens, you can ignore the event, call MyThread::stop(), and then when the QThread::finished() signal arrives, you can actually close the window.

The downside is that the stop() call will actually block while it tries to acquire the mutex. Given the way this code is written, the blocking will probably be very short, but hey, I hate blocking. Let’s see if we can dig up a better way to do this.

Way 2: With an event loop

If you have an event loop, you can use Qt’s meta-objects to talk to your thread. Let’s look at the same example as before, only this time with no locking or blocking.

Look mom! No locks! Now we have killed our thread, safely and gracefully. There is no chance of blocking, and we learned something about QMetaObject.

A couple items to note:

  • The doSomething() method is left as an exercise for the reader, but be careful about the QTimer interval. I used 0, which means it will be firing almost constantly.
  • The stop() method must be a slot in MyThread (and not just a regular method) or else invokeMethod() will return false and not actually re-invoke stop() for you.
  • You can pass arguments to your thread this way, but it requires a bit more fun with QMetaObject::invokeMethod().
  • You can reduce this whole thing to a magical macro that you could put at the top of your stop() method, saving you from having to write if(currentThread() this) at the top of every method. Hint: use the __FUNCTION__ macro.
  • To run this example code, you’ll need to #include these files: QThread, QTimer, QMetaObject, QMutexLocker, and QMutex
  • To call quit(), it may not actually be necessary to be running on the same QThread (it works for me without the QMetaObject), but this will be required when you start passing in data to your thread. Without it, your program could do unpredictable naughty things. I can’t find anything in the docs about whether quit() is thread safe.

I’ve found this QMetaObject approach the most effective and easiest way to pass data to QThreads safely, without blocking and without locks.

Happy threading!

The QFutureWatcher class allows monitoring a QFuture using signals and slots. More...

Header:#include <QFutureWatcher>
qmake: QT += core
Since: Qt 4.4
Inherits: QFutureWatcherBase

Note: All functions in this class are reentrant.

Public Functions

QFutureWatcher(QObject *parent = 0)
~QFutureWatcher()
QFuture<T> future() const
bool isCanceled() const
bool isFinished() const
bool isPaused() const
bool isRunning() const
bool isStarted() const
int progressMaximum() const
int progressMinimum() const
QString progressText() const
int progressValue() const
T result() const
T resultAt(int index) const
void setFuture(const QFuture<T> &future)
void setPendingResultsLimit(int limit)
void waitForFinished()
  • 12 public functions inherited from QFutureWatcherBase
  • 31 public functions inherited from QObject

Public Slots

void cancel()
void pause()
void resume()
void setPaused(bool paused)
void togglePaused()
  • 5 public slots inherited from QFutureWatcherBase
  • 1 public slot inherited from QObject

Signals

void canceled()
void finished()
void paused()
void progressRangeChanged(int minimum, int maximum)
void progressTextChanged(const QString &progressText)
void progressValueChanged(int progressValue)
void resultReadyAt(int index)
void resultsReadyAt(int beginIndex, int endIndex)
void resumed()
void started()
  • 10 signals inherited from QFutureWatcherBase
  • 2 signals inherited from QObject

Additional Inherited Members

  • 1 property inherited from QObject
  • 11 static public members inherited from QObject
  • 2 protected functions inherited from QFutureWatcherBase
  • 9 protected functions inherited from QObject

Detailed Description

The QFutureWatcher class allows monitoring a QFuture using signals and slots.

QFutureWatcher provides information and notifications about a QFuture. Use the setFuture() function to start watching a particular QFuture. The future() function returns the future set with setFuture().

For convenience, several of QFuture's functions are also available in QFutureWatcher: progressValue(), progressMinimum(), progressMaximum(), progressText(), isStarted(), isFinished(), isRunning(), isCanceled(), isPaused(), waitForFinished(), result(), and resultAt(). The cancel(), setPaused(), pause(), resume(), and togglePaused() functions are slots in QFutureWatcher.

Status changes are reported via the started(), finished(), canceled(), paused(), resumed(), resultReadyAt(), and resultsReadyAt() signals. Progress information is provided from the progressRangeChanged(), void progressValueChanged(), and progressTextChanged() signals.

Throttling control is provided by the setPendingResultsLimit() function. When the number of pending resultReadyAt() or resultsReadyAt() signals exceeds the limit, the computation represented by the future will be throttled automatically. The computation will resume once the number of pending signals drops below the limit.

Example: Starting a computation and getting a slot callback when it's finished:

Be aware that not all asynchronous computations can be canceled or paused. For example, the future returned by QtConcurrent::run() cannot be canceled; but the future returned by QtConcurrent::mappedReduced() can.

QFutureWatcher<void> is specialized to not contain any of the result fetching functions. Any QFuture<T> can be watched by a QFutureWatcher<void> as well. This is useful if only status or progress information is needed; not the actual result data.

See also QFuture and Qt Concurrent.

Member Function Documentation

QFutureWatcher::QFutureWatcher(QObject *parent = 0)

Constructs a new QFutureWatcher with the given parent.

QFutureWatcher::~QFutureWatcher()

Destroys the QFutureWatcher.

[slot] void QFutureWatcher::cancel()

Cancels the asynchronous computation represented by the future(). Note that the cancelation is asynchronous. Use waitForFinished() after calling cancel() when you need synchronous cancelation.

Currently available results may still be accessed on a canceled QFuture, but new results will not become available after calling this function. Also, this QFutureWatcher will not deliver progress and result ready signals once canceled. This includes the progressValueChanged(), progressRangeChanged(), progressTextChanged(), resultReadyAt(), and resultsReadyAt() signals.

Be aware that not all asynchronous computations can be canceled. For example, the QFuture returned by QtConcurrent::run() cannot be canceled; but the QFuture returned by QtConcurrent::mappedReduced() can.

[signal] void QFutureWatcher::canceled()

This signal is emitted if the watched future is canceled.

[signal] void QFutureWatcher::finished()

This signal is emitted when the watched future finishes.

Call

QFuture<T> QFutureWatcher::future() const

Returns the watched future.

See also setFuture().

bool QFutureWatcher::isCanceled() const

Returns true if the asynchronous computation has been canceled with the cancel() function; otherwise returns false.

Be aware that the computation may still be running even though this function returns true. See cancel() for more details.

bool QFutureWatcher::isFinished() const

Returns true if the asynchronous computation represented by the future() has finished, or if no future has been set; otherwise returns false.

bool QFutureWatcher::isPaused() const

Returns true if the asynchronous computation has been paused with the pause() function; otherwise returns false.

Be aware that the computation may still be running even though this function returns true. See setPaused() for more details.

See also setPaused() and togglePaused().

bool QFutureWatcher::isRunning() const

Returns true if the asynchronous computation represented by the future() is currently running; otherwise returns false.

bool QFutureWatcher::isStarted() const

Returns true if the asynchronous computation represented by the future() has been started; otherwise returns false.

[slot] void QFutureWatcher::pause()

Pauses the asynchronous computation represented by the future(). This is a convenience method that simply calls setPaused(true).

See also resume().

[signal] void QFutureWatcher::paused()

This signal is emitted when the watched future is paused.

See also setPaused().

int QFutureWatcher::progressMaximum() const

Returns the maximum progressValue().

See also progressValue() and progressMinimum().

int QFutureWatcher::progressMinimum() const

Returns the minimum progressValue().

See also progressValue() and progressMaximum().

[signal] void QFutureWatcher::progressRangeChanged(intminimum, intmaximum)

The progress range for the watched future has changed to minimum and maximum

QString QFutureWatcher::progressText() const

Returns the (optional) textual representation of the progress as reported by the asynchronous computation.

Be aware that not all computations provide a textual representation of the progress, and as such, this function may return an empty string.

[signal] void QFutureWatcher::progressTextChanged(const QString &progressText)

This signal is emitted when the watched future reports textual progress information, progressText.

int QFutureWatcher::progressValue() const

Returns the current progress value, which is between the progressMinimum() and progressMaximum().

See also progressMinimum() and progressMaximum().

[signal] void QFutureWatcher::progressValueChanged(intprogressValue)

This signal is emitted when the watched future reports progress, progressValue gives the current progress. In order to avoid overloading the GUI event loop, QFutureWatcher limits the progress signal emission rate. This means that listeners connected to this slot might not get all progress reports the future makes. The last progress update (where progressValue equals the maximum value) will always be delivered.

T QFutureWatcher::result() const

Returns the first result in the future(). If the result is not immediately available, this function will block and wait for the result to become available. This is a convenience method for calling resultAt(0).

See also resultAt().

T QFutureWatcher::resultAt(intindex) const

Returns the result at index in the future(). If the result is not immediately available, this function will block and wait for the result to become available.

See also result().

[signal] void QFutureWatcher::resultReadyAt(intindex)

This signal is emitted when the watched future reports a ready result at index. If the future reports multiple results, the index will indicate which one it is. Results can be reported out-of-order. To get the result, call future().result(index);

[signal] void QFutureWatcher::resultsReadyAt(intbeginIndex, intendIndex)

This signal is emitted when the watched future reports ready results. The results are indexed from beginIndex to endIndex.

[slot] void QFutureWatcher::resume()

Resumes the asynchronous computation represented by the future(). This is a convenience method that simply calls setPaused(false).

Orders

See also pause().

[signal] void QFutureWatcher::resumed()

Qt Signal Slot Call Ordering

This signal is emitted when the watched future is resumed.

void QFutureWatcher::setFuture(const QFuture<T> &future)

Starts watching the given future.

One of the signals might be emitted for the current state of the future. For example, if the future is already stopped, the finished signal will be emitted.

To avoid a race condition, it is important to call this function after doing the connections.

See also future().

[slot] void QFutureWatcher::setPaused(boolpaused)

If paused is true, this function pauses the asynchronous computation represented by the future(). If the computation is already paused, this function does nothing. This QFutureWatcher will stop delivering progress and result ready signals while the future is paused. Signal delivery will continue once the computation is resumed.

If paused is false, this function resumes the asynchronous computation. If the computation was not previously paused, this function does nothing.

Be aware that not all computations can be paused. For example, the QFuture returned by QtConcurrent::run() cannot be paused; but the QFuture returned by QtConcurrent::mappedReduced() can.

See also paused(), pause(), resume(), and togglePaused().

void QFutureWatcher::setPendingResultsLimit(intlimit)

Qt Signal Slot Call Order

The setPendingResultsLimit() provides throttling control. When the number of pending resultReadyAt() or resultsReadyAt() signals exceeds the limit, the computation represented by the future will be throttled automatically. The computation will resume once the number of pending signals drops below the limit.

[signal] void QFutureWatcher::started()

This signal is emitted when this QFutureWatcher starts watching the future set with setFuture().

Qt Signal Slot Call Orders

[slot] void QFutureWatcher::togglePaused()

Toggles the paused state of the asynchronous computation. In other words, if the computation is currently paused, calling this function resumes it; if the computation is running, it becomes paused. This is a convenience method for calling setPaused(!isPaused()).

See also setPaused(), pause(), and resume().

void QFutureWatcher::waitForFinished()

Waits for the asynchronous computation to finish (including cancel()ed computations).