我找到了几个具有自动完成功能的PyQt4 QComboBox的优秀示例(例如How do I Filter the PyQt QCombobox Items based on the text input?),但它们都使用setModel和setSourceModel ...等等。
是否可以在不使用模型的情况下在PyQt4中创建自动完成QComboBox?
答案 0 :(得分:2)
使用smitkpatel的评论......我找到了一个有效的setCompleter示例。它由flutefreak在QComboBox with autocompletion works in PyQt4 but not in PySide发布。
from PyQt4 import QtCore
from PyQt4 import QtGui
class AdvComboBox(QtGui.QComboBox):
def __init__(self, parent=None):
super(AdvComboBox, self).__init__(parent)
self.setFocusPolicy(QtCore.Qt.StrongFocus)
self.setEditable(True)
# add a filter model to filter matching items
self.pFilterModel = QtGui.QSortFilterProxyModel(self)
self.pFilterModel.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)
self.pFilterModel.setSourceModel(self.model())
# add a completer, which uses the filter model
self.completer = QtGui.QCompleter(self.pFilterModel, self)
# always show all (filtered) completions
self.completer.setCompletionMode(QtGui.QCompleter.UnfilteredPopupCompletion)
self.setCompleter(self.completer)
# connect signals
def filter(text):
print "Edited: ", text, "type: ", type(text)
self.pFilterModel.setFilterFixedString(str(text))
self.lineEdit().textEdited[unicode].connect(filter)
self.completer.activated.connect(self.on_completer_activated)
# on selection of an item from the completer, select the corresponding item from combobox
def on_completer_activated(self, text):
if text:
index = self.findText(str(text))
self.setCurrentIndex(index)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
combo = AdvComboBox()
names = ['bob', 'fred', 'bobby', 'frederick', 'charles', 'charlie', 'rob']
combo.addItems(names)
combo.resize(300, 40)
combo.show()
sys.exit(app.exec_())