例如,我的 QComboBox 下拉列表中有这三个项目
chicken soup
chilli peppers
grilled chicken
输入“ch”将匹配“鸡汤”和“辣椒”,但不匹配“烤鸡”。
我想要的是能够输入“ch”并匹配所有这些,或者更具体地说,“chicken”并匹配“鸡汤”和“烤鸡”。
参考: https ://bugreports.qt-project.org/browse/QTBUG-7830
以下代码只能运行一次,为什么?如果输入 'a',所有包含 'a' 的字符串都会正确显示,返回 3 个结果,'Jane Doe','Albert Einstein', 'Alfred E Newman' 但如果继续输入 'n',没有结果显示在下拉菜单中。
编辑:它可以工作,但弹出的QListView没有正确显示(如果你按下箭头键,匹配的项目将显示在组合框编辑区域,但下拉列表不显示)
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import QtGui,QtCore
import sys
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
class MyGui(QDialog):
def __init__(self, parent=None):
super(MyGui,self).__init__(parent)
model = QtGui.QStringListModel()
wordList = ['John Doe','Jane Doe','Albert Einstein', 'Alfred E Newman']
model.setStringList(wordList)
layout = QtGui.QVBoxLayout(self)
self.line = QtGui.QLineEdit(self)
layout.addWidget(self.line)
self.combobox = QComboBox(parent)
layout.addWidget(self.combobox)
self.combobox.addItems(wordList)
self.combobox.setEditable(True)
self.setLayout(layout)
complete = CustomQCompleter2(self)
complete.setModel(model)
complete.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
complete.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
complete.setWrapAround(False)
self.line.setCompleter(complete)
self.combobox.setCompleter(complete)
self.combobox.setEditText('')
self.setGeometry(200, 100, 400, 300)
class CustomQCompleter2(QCompleter):
def __init__(self, parent=None):
super(CustomQCompleter2, self).__init__(parent)
self.local_completion_prefix = ""
self.source_model = None
def setModel(self, model):
self.source_model = model
super(CustomQCompleter2, self).setModel(self.source_model)
def updateModel(self):
local_completion_prefix = self.local_completion_prefix
class InnerProxyModel(QSortFilterProxyModel):
def filterAcceptsRow(self, sourceRow, sourceParent):
index0 = self.sourceModel().index(sourceRow, 0, sourceParent)
searchStr = local_completion_prefix.lower()
modelStr = self.sourceModel().data(index0,Qt.DisplayRole).toString().toLower()
print searchStr,' in ',modelStr, searchStr in modelStr
return searchStr in modelStr
proxy_model = InnerProxyModel()
proxy_model.setSourceModel(self.source_model)
super(CustomQCompleter2, self).setModel(proxy_model)
print 'match :',proxy_model.rowCount()
def splitPath(self, path):
self.local_completion_prefix = str(path)
self.updateModel()
return ""
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
gui = MyGui()
gui.show()
sys.exit(app.exec_())