Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to distinguish between programmatic index changes and user selection index changes?

Tags:

qt

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?

like image 557
Walt Dizzy Records Avatar asked Jul 11 '14 04:07

Walt Dizzy Records


Video Answer


2 Answers

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);
like image 68
Oleh Prypin Avatar answered Oct 30 '22 09:10

Oleh Prypin


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!

like image 33
xarxer Avatar answered Oct 30 '22 09:10

xarxer