Qt Signals And Slots Without Event Loop

Qt Signals And Slots Without Event Loop Average ratng: 3,5/5 207 votes

When we change a widget in GUI programming, we often want another widget to be notified. More generally, we want objects of any kind to be able to communicate with one another. For instance, if a user clicks a Close button, we probably want the window's close() function to be called. Signals and slots are Qt Jambi's mechanism for such communication between objects.

In this overview, we will examine how to implement and use signals and slots in Qt Jambi. We look at how the mechanism works, its intended usage, and give an example.

The main event loop receives events from the window system and dispatches these to the application widgets. Generally speaking, no user interaction can take place before calling exec. As a special case, modal widgets like QMessageBox can be used before calling exec, because modal widgets use their own local event loop. A QueuedConnection will post an event to the event loop to eventually be handled. When posting an event (in QCoreApplication::postEvent), the event will be pushed in a per-thread queue (QThreadData::postEventList). The event queued is protected by a mutex, so there is no race conditions when threads push events to another thread. An abstract view of some signals and slots connections In Qt we have an alternative to the callback technique. We use signals and slots. A signal is emitted when a particular event occurs. Qt's widgets have many pre-defined signals, but we can always subclass to add our own. A slot is a function that is called in reponse to a particular signal.

Signal and Slots

  • Signals and Slots. In Qt, we have an alternative to the callback technique: We use signals and slots. A signal is emitted when a particular event occurs. Qt's widgets have many predefined signals, but we can always subclass widgets to add our own signals to them. A slot is a function that is called in response to a particular signal.
  • The event handler can emit the signals without connecting a signal to a slot, which then emits several signals. Qt is an event-based system. The GUI thread enters the event loop, when QCoreApplication::exec is called.
A signal is emitted when a particular event occurs. Qt Jambi's widgets have many predefined signals, but we can always subclass widgets to add our own signals to them. A slot is a method that is called in response to a particular signal. Qt's widgets have many pre-defined slots, but it is common practice to subclass widgets and add your own slots so that you can handle the signals that you are interested in. Qt signals and slots without event loop youtube
The signals and slots mechanism is type safe: The signature of a signal must match the signature of the receiving slot. Signals and slots are loosely coupled: A class which emits a signal neither knows nor cares which slots receive the signal. Qt Jambis's signals and slots mechanism ensures that if you connect a signal to a slot, the slot will be called with the signal's parameters at the right time.

All classes that inherit from QSignalEmitter - which is an ancestor of all Qt Jambi classes - or one of its subclasses (e.g., QWidget) can contain signals and slots. Signals are emitted by objects when they change their state in a way that may be interesting to other objects. This is all the object does to communicate. It does not know or care whether anything is receiving the signals it emits. This is true information encapsulation, and ensures that the object can be used as a software component.

All normal member methods can be used as slots, so there are no specific requirements for a method to function as a slot. Just as an object does not know if anything receives its signals, a slot does not know if it has any signals connected to it. This ensures that truly independent components can be created with Qt Jambi.

You can connect as many signals as you want to a single slot, and a signal can be connected to as many slots as you need. It is even possible to connect a signal directly to another signal. (This will emit the second signal immediately whenever the first is emitted.)

Together, signals and slots make up a powerful component programming mechanism.

An Example

A minimal Java class using signals and slots may read: The class manages a counter, which is stored in the private member value. The signal valueChanged is emitted whenever valueWithout changes. We will now go through the class step-by-step to describe how signals are created and emitted. Signals in Qt Jambi are implemented in classes named Signal1, Signal2 to Signal9. The number of the class indicates the number of parameters the signal has. The type of each parameter is specified as a generic. It is customary to declare signals as public rather than to provide access methods for them. The getter for value is annotated with @QtBlockedSlot. This prevents the method from being used as a slot. The annotation is mostly provided for consitency with Qt, in which functions must explicitly be declared as slots. To emit a signal, you simply invoke its emit method with the necessary parameters (all signal classes implements an emit method). The signal will then invoke the slots and other signals it is connected to.

Note that the signal is only emitted if val != value. This prevents infinite looping in the case of cyclic connections (e.g., if b.valueChanged() were connected to a.setValue()). We move on the see how signals are connected to slots. When you connect a signal to a slot, you specify the object that will receive the signal and the method signature of the slot. It is only the type of the method parameters that should be specified and not the parameter names.

Calling a.setValue(12) makes a emit a valueChanged(12) signal, which b will receive in its setValue() slot, i.e. b.setValue(12) is called. Then b emits the same valueChanged() signal, but since no slot has been connected to b's valueChanged() signal, the signal is ignored.

A signal is emitted for every connection you make; if you duplicate a connection, two signals will be emitted. You can always break a connection using the signal classes disconnect() method.

Signals

Signals are emitted by an object when its internal state has changed in some way that might be interesting to the object's client or owner. Only the class that defines a signal and its subclasses should emit the signal.

When a signal is emitted, the slots connected to it are executed immediately, just like a normal method call. When this happens, the signals and slots mechanism is totally independent of any GUI event loop. Execution of the code following call to emit will occur once all slots have returned. The situation is slightly different when using queued connections; in such a case, the code following the call to the signals emit method will continue immediately, and the slots will be executed later.

If several slots are connected to one signal, the slots will be executed one after the other when the signal is emitted.

Slots

A slot is called when a signal connected to it is emitted. Slots are normal Java methods and can be invoked normally; when we talk about a slot, we simply mean a method that happens to be used as a slot.

Since slots are normal member methods, they follow the normal Java rules when called directly. However, as slots, they can be invoked by any component, regardless of its access level, via a signal-slot connection. This means that a signal emitted from an instance of an arbitrary class can cause a private slot to be invoked in an instance of an unrelated class.

Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies)Trademarks

EnArBgDeElEsFaFiFrHiHuItJaKnKoMsNlPlPtRuSqThTrUkZh

Qt signals and slots without event loops

This page was used to describe the new signal and slot syntax during its development. The feature is now released with Qt 5.

  • Differences between String-Based and Functor-Based Connections (Official documentation)
  • Introduction (Woboq blog)
  • Implementation Details (Woboq blog)

Note: This is in addition to the old string-based syntax which remains valid.

  • 1Connecting in Qt 5
  • 2Disconnecting in Qt 5
  • 4Error reporting
  • 5Open questions

Connecting in Qt 5

There are several ways to connect a signal in Qt 5.

Old syntax

Qt 5 continues to support the old string-based syntax for connecting signals and slots defined in a QObject or any class that inherits from QObject (including QWidget)

New: connecting to QObject member

Here's Qt 5's new way to connect two QObjects and pass non-string objects:

Pros

  • Compile time check of the existence of the signals and slot, of the types, or if the Q_OBJECT is missing.
  • Argument can be by typedefs or with different namespace specifier, and it works.
  • Possibility to automatically cast the types if there is implicit conversion (e.g. from QString to QVariant)
  • It is possible to connect to any member function of QObject, not only slots.

Cons

Slots
  • More complicated syntax? (you need to specify the type of your object)
  • Very complicated syntax in cases of overloads? (see below)
  • Default arguments in slot is not supported anymore.

New: connecting to simple function

The new syntax can even connect to functions, not just QObjects:

Pros

Qt Signals And Slots Without Event Loop Download

  • Can be used with std::bind:
  • Can be used with C++11 lambda expressions:

Cons

  • There is no automatic disconnection when the 'receiver' is destroyed because it's a functor with no QObject. However, since 5.2 there is an overload which adds a 'context object'. When that object is destroyed, the connection is broken (the context is also used for the thread affinity: the lambda will be called in the thread of the event loop of the object used as context).

Disconnecting in Qt 5

As you might expect, there are some changes in how connections can be terminated in Qt 5, too.

Old way

You can disconnect in the old way (using SIGNAL, SLOT) but only if

  • You connected using the old way, or
  • If you want to disconnect all the slots from a given signal using wild card character

Symetric to the function pointer one

Only works if you connected with the symmetric call, with function pointers (Or you can also use 0 for wild card)In particular, does not work with static function, functors or lambda functions.

New way using QMetaObject::Connection

Works in all cases, including lambda functions or functors.

Asynchronous made easier

With C++11 it is possible to keep the code inline

Here's a QDialog without re-entering the eventloop, and keeping the code where it belongs:

Another example using QHttpServer : http://pastebin.com/pfbTMqUm

Error reporting

Tested with GCC.

Fortunately, IDEs like Qt Creator simplifies the function naming

Missing Q_OBJECT in class definition

Qt Signals And Slots Without Event Loops

Type mismatch

Open questions

Default arguments in slot

Qt Signals And Slots Without Event Loop

If you have code like this:

The old method allows you to connect that slot to a signal that does not have arguments.But I cannot know with template code if a function has default arguments or not.So this feature is disabled.

There was an implementation that falls back to the old method if there are more arguments in the slot than in the signal.This however is quite inconsistent, since the old method does not perform type-checking or type conversion. It was removed from the patch that has been merged.

Overload

As you might see in the example above, connecting to QAbstractSocket::error is not really beautiful since error has an overload, and taking the address of an overloaded function requires explicit casting, e.g. a connection that previously was made as follows:

connect(mySpinBox, SIGNAL(valueChanged(int)), mySlider, SLOT(setValue(int));

cannot be simply converted to:

...because QSpinBox has two signals named valueChanged() with different arguments. Instead, the new code needs to be:

Unfortunately, using an explicit cast here allows several types of errors to slip past the compiler. Adding a temporary variable assignment preserves these compile-time checks:

Some macro could help (with C++11 or typeof extensions). A template based solution was introduced in Qt 5.7: qOverload

The best thing is probably to recommend not to overload signals or slots …

… but we have been adding overloads in past minor releases of Qt because taking the address of a function was not a use case we support. But now this would be impossible without breaking the source compatibility.

Disconnect

Should QMetaObject::Connection have a disconnect() function?

The other problem is that there is no automatic disconnection for some object in the closure if we use the syntax that takes a closure.One could add a list of objects in the disconnection, or a new function like QMetaObject::Connection::require


Callbacks

Function such as QHostInfo::lookupHost or QTimer::singleShot or QFileDialog::open take a QObject receiver and char* slot.This does not work for the new method.If one wants to do callback C++ way, one should use std::functionBut we cannot use STL types in our ABI, so a QFunction should be done to copy std::function.In any case, this is irrelevant for QObject connections.

Qt Signals And Slots Without Event Loop Youtube

Retrieved from 'https://wiki.qt.io/index.php?title=New_Signal_Slot_Syntax&oldid=34943'