1

我有多列的数据(如“名字”/“姓氏”或“邮政编码”/“地名”),我现在想要(类似于)一个仅从每列的开头匹配的 qcompleter .

这意味着“a”的输入将显示诸如“ A ndrea Miller”或“John A dams”之类的建议,而不是“J a ne Doe”或“Tom M a sters”。

任何提示如何实现这一点?

4

1 回答 1

3

一种解决方法是禁用 QCompleter 过滤并使用 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_())
于 2019-11-20T16:00:48.437 回答