Search code examples
python-3.xpyqt5

Using PyQt5, How do I make a QComboBox searchable?


I am using PyQt5 to make a GUI. On it, I have a QComboBox that has a dropdown list that has over 400 items. I was wondering if there is any way in which I can type into the QComboBox to search for a matching case?


Solution

  • You could use a QCompleter for this. For an editable QComboBox a QCompleter is created automatically. This completer performs case insensitive inline completion but you can adjust that if needed, for example

    from PyQt5 import QtWidgets
    from itertools import product
    
    app = QtWidgets.QApplication([])
    
    # wordlist for testing
    wordlist = [''.join(combo) for combo in product('abc', repeat = 4)]
    
    combo = QtWidgets.QComboBox()
    combo.addItems(wordlist)
    
    # completers only work for editable combo boxes. QComboBox.NoInsert prevents insertion of the search text
    combo.setEditable(True)
    combo.setInsertPolicy(QtWidgets.QComboBox.NoInsert)
    
    # change completion mode of the default completer from InlineCompletion to PopupCompletion
    combo.completer().setCompletionMode(QtWidgets.QCompleter.PopupCompletion)
    
    combo.show()
    app.exec()