我有多列数据(如"名字"/"姓氏"或"邮政编码"/"地名"(,现在我想要一个只从每列开始匹配的qcompleter。
这意味着"a"的输入将显示类似">aandrea Miller"或"Johnadams"的建议,而不是"Jane Doe"或"Tom Masters"。
有关于如何实现这一点的提示吗?
解决方法是禁用QComplete过滤并使用QSortFilterProxyModel进行自定义过滤:
import sys
from PySide2 import QtCore, QtWidgets
class FilterModel(QtCore.QSortFilterProxyModel):
def __init__(self, parent=None):
super().__init__(parent)
self._prefix = ""
@property
def prefix(self):
return self._prefix
@prefix.setter
def prefix(self, prefix):
self._prefix = prefix.lower()
self.invalidateFilter()
def filterAcceptsRow(self, sourceRow, sourceParent):
if not self.prefix:
return True
text = (
self.sourceModel()
.index(sourceRow, self.filterKeyColumn(), sourceParent)
.data()
)
for word in text.split():
if word.lower().startswith(self.prefix):
return True
return False
class Completer(QtWidgets.QCompleter):
def setModel(self, model):
proxy_internal_model = FilterModel(self)
proxy_internal_model.setSourceModel(model)
model.setParent(proxy_internal_model)
super().setModel(proxy_internal_model)
def splitPath(self, path):
if isinstance(self.model(), FilterModel):
self.model().prefix = path
return [""]
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QLineEdit()
texts = ["Andrea Miller", "John Adams", "Jane Doe", "Tom Masters"]
completer = Completer(w)
completer.setModel(QtCore.QStringListModel(texts, w))
w.setCompleter(completer)
w.show()
sys.exit(app.exec_())