PDA

View Full Version : Is there a way to distinguish between programmatic index changes and user selection?



jmalicke
11th July 2014, 06:30
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?

anda_skoa
11th July 2014, 08:55
You have two options:

1) block the signal when you change the index programatically


comboBox->blockSignals(true);
comboBox->setCurrentIndex(number);
comboBox->blockSignals(false);


2) have a state flag that tells you that you are changing the UI programmatically


void MyClass::updateUiProgrammatically()
{
// bool MyClass::m_nonUserChange
m_nonUserChange = true;

// peform changes to the U

m_nonUserChange = false;
}

void MyClass::onCurrentIndexChanged(int index)
{
if (m_nonUserChange) return; // ignore programmatic changes
}


The first solution is more compact, but since it blocks the emitting of the signal, none of the slots will be called.

For example if you had a slider and a spinbox connected to each other to work as a combined input for a single value, then blocking the signal on, say, the slider would mean you could get the two values separated.

Cheers,
_