Qt 4: The book

Page 40

1 Basics, Tools, and First Code

We will place the three widgets in turn (that is, from top to bottom) into a vertical layout. To do this the QSpinBox class contributes the spin box element, and the QSlider is correspondingly responsible for the slider. To ensure synchronization of the widgets, we use four connect() calls (Figure 1.7): if the value of the spin box changes, then the label and the slider must be updated; if the status of the slider varies, the label and the spin box need to be brought up-to-date. (Note that because the spinBox, label, and slider variables are already pointer variables that reference the widgets, we don’t have to take their addresses using the & operator, as we did in the previous example.) Figure 1.7: The example program shows that a signal can be connected to several slots.

QSlider

QSpinBox

setValue(int)

setValue(int)

valueChanged(int)

valueChanged(int)

QLabel setNum(int)

A change made to the value by the user is reported by the QSpinBox and QSlider classes via the signal QSpinBox::valueChanged(int) or QSlider::valueChanged(int). In each case, the integer argument indicated by the int keyword, which the signal transmits to the slot, specifies the new value of the spin box or the slider. A new value for the label is set using the QLabel::setNum(int) slot, a function that is called with an integer value as an argument. The spin box and the slider are handled similarly using the slots QSpinBox::setValue(int) and QSlider::setValue(int). The arrows in Figure 1.7 show that a signal can be connected to several slots and that a slot can react to several signals. For example, if the QSpinBox object sends out the signal valueChanged(int) with the value 5, both the setNum(int) slot of the QLabel object and the setValue(int) function of the QSlider object are called with the value 5. Qt does not specify the order in which this happens. Either the label or the slider can be updated first, and the exact behavior may be unpredictable. Still, all three widgets will eventually display the value 5. In this example the signals and slots use the same argument list because no type conversion takes place in signal/slot connections. Thus the setText() slot of the QLabel object, which takes a string as an argument and displays it, cannot be connected to the valueChanged(int) signal, since the int argument will not be converted to a string.

38


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.