首页 > 解决方案 > 使用 PyQt5,如何使 QComboBox 可搜索?

问题描述

我正在使用 PyQt5 制作 GUI。在它上面,我有一个 QComboBox,它有一个包含 400 多个项目的下拉列表。我想知道是否有任何方法可以输入 QComboBox 来搜索匹配的案例?

标签: python-3.xpyqt5

解决方案


您可以QCompleter为此使用 a 。对于可编辑QComboBox的 aQCompleter是自动创建的。此完成程序执行不区分大小写的内联完成,但您可以根据需要进行调整,例如

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()

推荐阅读