Search code examples
c++qtqt5qcombobox

Prevent editable QComboBox selection from changing when item list modified


I have an editable QComboBox containing a list of ID numbers.

The ID numbers represent devices attached to the system. The devices are frequently added and removed at runtime.

The intent of the editable combo box is to contain, in its list, the list of IDs currently attached, for easy selection, but at the same time allow the user to manually enter IDs of devices not currently present. Also, it's valid to enter an empty string for the ID.

Basically I want to provide the user with a way to enter an arbitrary (or no) ID, with the added bonus of a quick selection of devices currently attached (which changes at runtime).

I am not currently using a list model to maintain the list, I'm just using the QComboBox's add and remove functions.

I need the selection to not change if devices are added or removed. However, I'm running into the following problems:

  • When the currently entered ID (either manually or by list selection) is removed from the list, the selection is changed to another ID in the list.
  • When the list is empty and an ID is entered manually, or no ID is entered at all, the selection is changed when an ID is added to the list.

Is there a way to make it so that adding and removing items from the combo box never, ever modifies the selection in the edit box? Or even some other UI element that accomplishes my goal?


Solution

  • Before updating the combo box, save the currently selected ID (or the blank string) to a temp. variable. After modifying the combo box contents, check if that ID still exists in the combo box (e.g. with findText()). If it does, select it with setCurrentIndex(). If it does not, set it with setCurrentText() or setEditText().