Skip to content

Instantly share code, notes, and snippets.

@heuristicus
Last active April 5, 2022 13:29
Show Gist options
  • Save heuristicus/7e1fb5a55a5f569b6548ec19a9d69b24 to your computer and use it in GitHub Desktop.
Save heuristicus/7e1fb5a55a5f569b6548ec19a9d69b24 to your computer and use it in GitHub Desktop.
Implement a combobox where the entries are filtered by the line edit
// Initialise the combobox for the edge selection
// listmodel stores the actual data. This will be populated when we get a map update
edgeIDModel = new QStringListModel();
// Set the model for the combobox as the base stringlist model. If we use the same filter model for both the
// combobox and the completer, there will be weird behaviour, probably because the two objects are fighting
// to define what is in the list of strings.
actionComboBox->setModel(edgeIDModel);
// Need a completer so that the combobox pops up with possible options given typed text
edgeIDCompleter = new QCompleter();
edgeIDCompleter->setParent(parent);
edgeIDCompleter->setCompletionMode(QCompleter::PopupCompletion);
// Make a filter model for the completer which allows sorting and filtering of data in the list model
edgeIDFilter = new QSortFilterProxyModel();
edgeIDFilter->setSourceModel(edgeIDModel);
edgeIDFilter->setFilterCaseSensitivity(Qt::CaseSensitive);
// the completer uses a different model to the combobox, but it points to the same base data (?)
edgeIDCompleter->setModel(edgeIDFilter);
// set the completer on the combobox so it will do the filtering
actionComboBox->setCompleter(edgeIDCompleter);
// Connect up the line edit to the filter so that when text is edited it modifies the
// completer's model (and not the one of the combobox)
connect(actionComboBox->lineEdit(), SIGNAL(textEdited(QString)), edgeIDFilter, SLOT(setFilterFixedString(QString)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment