Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Qt handle a suposedly infinite loop of event emits?

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

like image 462
fonini Avatar asked Mar 15 '14 00:03

fonini


1 Answers

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 if value != m_value. This prevents infinite looping in the case of cyclic connections (e.g., if b.valueChanged() were connected to a.setValue()).

So in this case it's a safety feature of setValue. This is also documented in the setValue function:

setValue() will emit valueChanged() 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.

like image 176
Zeta Avatar answered Nov 02 '22 03:11

Zeta