Built-in variables: sender

Strictly speaking, sender is not a real built-in variable but a hidden parameter available exclusively in all slot methods. It refers to the object, which has sent the signal to the slot method.


object sender


The variable sender refers to the object, which has sent or post (see also idlesignal and notifyobservers) a signal to the slot method. By using this variable the implementation of the slot method can access and evaluate the original sender object. As such the variable sender is valid only within the implementation of a slot method.

You can evaluate the variable sender within expressions inside a slot method wherever an operand of data type object is allowed. Usually, you do it to determine which of the possible (well known) sender objects was the real sender. Assuming, you have a single slot method connected to three different push buttons Button1, Button2 and Button3, then you can distinguish in the slot method which of the three buttons was the sender of the signal:

if ( sender == Button1 ) trace "User has pressed Button 1"; if ( sender == Button2 ) trace "User has pressed Button 2"; if ( sender == Button3 ) trace "User has pressed Button 3";

Within the slot method implementation you can also perform a cast on the sender object to a known class in order to test, whether the object is an instance of this class. Subsequently, if the cast succeed, you can easily access the members of sender object. This is useful when e.g. a single slot is connected to several event handler objects and within the slot method you need to evaluate the current state of the sending handler:

// Try to cast the sender object to the key press handler class var Core::KeyPressHandler keyHandler = (Core::KeyPressHandler)sender; // If the cast failed? if ( keyHandler == null ) return; // Now the members of the handler object can be accessed ... var Core::KeyCode keyCode = keyHandler.Code; var bool keyPressed = keyHandler.Down;