Is there a way to distinguish between changes in program indexes and changes in the user selection index?

I have a QComboBox. I have two use cases. In one case, the combined block is programmatically modified to have a new index through setCurrentIndex (). In another use case, the user clicks and selects a new selection with a list with the mouse.

Both of these use cases trigger the QComboBox :: currentIndexChanged (int) signal. This is a serious problem for the code I'm trying to execute. In the old structure (not Qt), a similar callback mechanism will be called only if the user has selected an element, and not if the index has changed programmatically.

How can I simulate this behavior in Qt?

+4
source share
2 answers

I remember that there is a way to pause event triggering in Qt, so you can do this before and after the change currentIndex.

Ah, and here it is:

bool oldState = comboBox->blockSignals(true);
comboBox->setCurrentIndex(5);
comboBox->blockSignals(oldState);
+5
source

You can listen to signals QComboBox::activated(int index)and QComboBox::currentIndexChanged(int index).

If the user changes the value of the signals will be rejected QComboBox::activated(int index)and QComboBox::currentIndexChanged(int index).

If the value changes programmatically, only a signal will be emitted QComboBox::currentIndexChanged(int index). Thus, the first signal means: "The user has 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 this helps!

+8
source

Source: https://habr.com/ru/post/1548008/


All Articles