Skip to content

Instantly share code, notes, and snippets.

@rBrenick
Last active September 4, 2022 16:53
Show Gist options
  • Save rBrenick/cb4c29f8a2d094e9df3e321a87eceb04 to your computer and use it in GitHub Desktop.
Save rBrenick/cb4c29f8a2d094e9df3e321a87eceb04 to your computer and use it in GitHub Desktop.
Quick function to make a QComboBox into a searchable list
__author__ = "RichardBrenick@gmail.com"
__created__ = "2022-09-03"
"""
This is mostly a recreation of this stack overflow answer: https://stackoverflow.com/a/65408354
With some changes to make it callable after initialization.
"""
from PySide2 import QtCore, QtWidgets
def make_combo_box_searchable(combo_box):
combo_box.setFocusPolicy(QtCore.Qt.StrongFocus)
combo_box.setEditable(True)
combo_box.setInsertPolicy(QtWidgets.QComboBox.NoInsert)
filter_model = QtCore.QSortFilterProxyModel(combo_box)
filter_model.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)
filter_model.setSourceModel(combo_box.model())
completer = QtWidgets.QCompleter(filter_model, combo_box)
completer.setCompletionMode(QtWidgets.QCompleter.UnfilteredPopupCompletion)
combo_box.setCompleter(completer)
combo_box.lineEdit().textEdited.connect(filter_model.setFilterFixedString)
# example/test window
if __name__ == "__main__":
import sys
import random
app = QtWidgets.QApplication(sys.argv)
example_texts = ["Pose_{}".format(i) for i in range(100)]
for special_text in ["important item", "other important item", "very important item", "not that important", "something", "another thing in a list", "the most important"]:
example_texts.insert(random.randint(0, len(example_texts)), special_text)
example_combo_box = QtWidgets.QComboBox()
example_combo_box.addItems(example_texts)
make_combo_box_searchable(example_combo_box)
window = QtWidgets.QWidget()
window_layout = QtWidgets.QVBoxLayout()
window_layout.addWidget(example_combo_box)
window.setLayout(window_layout)
window.show()
app.exec_()
@rBrenick
Copy link
Author

rBrenick commented Sep 3, 2022

SearchableComboBox

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment