I have both a QSlider and a QSpinBox, and I wanted their values to be always equal, so I connected the slider's valueChanged(int)
signal to the spinbox' setValue(int)
slot, and vice versa: (of course, I also set the min and max values to be equal)
connect(delay_slider, SIGNAL(valueChanged(int)),
delay_spin, SLOT(setValue(int)));
connect(delay_spin, SIGNAL(valueChanged(int)),
delay_slider, SLOT(setValue(int)));
I tested, and it works (at least on my Ubuntu 12.04 LTS x86_64, g++ 4.6.3, Qt 4.8.1).
Now, I think that when I emit one of the signals, it will trigger the other, which will trigger the first one, which will trigger the other, etc. How does Qt handle that? Is there a document that describes the mechanisms used?
Obs: I called it a "loop of event emits" because this has nothing to do with the Qt Event Loop
That's just exactly the example from the Signals & Slots documentation:
Counter a, b; QObject::connect(&a, SIGNAL(valueChanged(int)), &b, SLOT(setValue(int))); a.setValue(12); // a.value() == 12, b.value() == 12 b.setValue(48); // a.value() == 12, b.value() == 48
Note that the
setValue()
function sets the value and emits the signal only ifvalue != m_value
. This prevents infinite looping in the case of cyclic connections (e.g., ifb.valueChanged()
were connected toa.setValue()
).
So in this case it's a safety feature of setValue
. This is also documented in the setValue
function:
setValue()
will emitvalueChanged()
if the new value is different from the old one.
If you change the value in your slider, it will emit, which will change the value in your spin, which will emit, which now doesn't change the value in your slider.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With