8.5.  Signals and Slots

[ fromfile: signals.xml id: signals ]

A signal is a message presented in a class definition like a void function declaration. It has a parameter list but no function body. A signal is part of the interface of a class. It looks like a function, but it is not invoked the same way – it is emitted by an object of that class.

A slot is usually a void member function. It can be called as a normal member function or it can be invoked indirectly by the QMetaObject system.

A signal of one object can be connected to the slots of one or more objects, provided the objects exist and the parameter lists are compatible from the signal to the slot.[68] The syntax of the connect statement is

  bool QObject::connect(senderQObjectPtr,
                       SIGNAL(signalName(argumentList)),
                       receiverQObjectPointer,
                       SLOT[69](slotName(argumentList))
                       optionalConnectionType);
 

Any QObject that has a signal can emit that signal. This produces indirect calls to all connected slots.

Arguments passed in the emit statement are accessible as parameters in the slot function, similar to a direct function call. The argument list is a way to transmit information from one object to another. The optionalConnectionType enables you to specify if you want synchronous (blocking) or asynchronous (queued) calls to the destination slots from the emit point. [70]

Section 1.11 discusses an example that employs a QInputDialog widget (Figure 8.5). When running that application, the user interacts with the first dialog by entering a value and then left-clicking on either the Cancel or the OK button.

Figure 8.5.  QInputDialog

QInputDialog

The left mouse button release event, which is the final step in a mouse-click, causes the chosen button widget to emit the clicked() signal. That signal is the culmination of a sequence of lower-level mouse events that pinpoint the location of the mouse pointer (inside the button's rectangle) and verify the correct order of mouse button operations. (For example, the left mouse button was pressed and then released while still inside the rectangle) In other words, mouse events have been combined to form a clicked() signal. The API of a well-designed widget should contain an adequate set of signals so that it is not necessary to work with low-level events unless you develop a custom widget.

[Tip] Tip

If you have multiple signals connected to the same slot, and need to know which QObject emitted the signal, you can call sender() from inside the slot, and it returns a pointer to that object.



[68] When the lists are assignment compatible, this means that corresponding parameters must be compatible. In Qt, the slot must have at least as many paramaters as the signal. The slot can ignore extra arguments.

[69] or signal

[70] Connection is not restricted to the current thread Section 17.2