I have a QComboBox. I have two use cases. In one use case, the combo box is programmatically changed to have a new index via setCurrentIndex(). In the other use case, the user clicks and selects a new combo box selection with the mouse.
Both of these use cases trigger the QComboBox::currentIndexChanged(int) signal. This is a major problem for the code I am trying to port. In the old framework (not Qt), a similar callback mechanism would be called only if the user selected an item and not if the index programmatically changed.
How can I mimic this behavior in Qt?
I remember there being a way to suspend triggering events in Qt, so you can do that, before and after changing currentIndex
.
Ah, and here it is:
bool oldState = comboBox->blockSignals(true);
comboBox->setCurrentIndex(5);
comboBox->blockSignals(oldState);
You can listen for the QComboBox::activated(int index)
and QComboBox::currentIndexChanged(int index)
signals.
If the user changes the value, both QComboBox::activated(int index)
and QComboBox::currentIndexChanged(int index)
signals will be emitted.
If the value changes programatically, only the QComboBox::currentIndexChanged(int index)
signal will be emitted. So basically, the former signal means "The user changed the index to this value".
Example:
int main(int argc, char* argv[]) {
QComboBox* combo = new QComboBox;
QObject::connect(combo, &QComboBox::activated, [&](int index) {
//User changed the value
});
}
I hope that helps!
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