- Game Programming using Qt 5 Beginner's Guide
- Pavel Strakhov Witold Wysota Lorenz Haas
- 265字
- 2021-08-27 18:30:55
Signals and slots
To trigger functionality as a response to something that happens in an application, Qt uses a mechanism of signals and slots. This is another important feature of the QObject class. It's based on connecting a notification (which Qt calls a signal) about a change of state in some object with a function or method (called a slot) that is executed when such a notification arises. For example, if a button is pressed, it emits (sends) a clicked() signal. If some method is connected to this signal, the method will be called whenever the button is pressed.
Signals can have arguments that serve as a payload. For example, an input box widget (QLineEdit) has a textEdited(const QString &text) signal that's emitted when the user edits the text in the input box. A slot connected to this signal will receive the new text in the input box as its argument (provided it has an argument).
Signals and slots can be used with all classes that inherit QObject (including all widgets). A signal can be connected to a slot, member function, or functor (which includes a regular global function). When an object emits a signal, any of these entities that are connected to that signal will be called. A signal can also be connected to another signal, in which case emitting the first signal will make the other signal be emitted as well. You can connect any number of slots to a single signal and any number of signals to a single slot.