3

据我所知,QCompleter 只能为以 QLineEdit 中输入的相同字符串开头的字符串提供建议的完成列表。我希望它提出任何包含它作为子字符串的字符串,无论它是在它的开头还是在它的中间......也就是说,对于列表listOfStrings和给定的substring,我希望它建议每个string in [s for s in listOfStrings if substring in s] 而不是实际的 [s for s in listOfStrings if substring == s[:len(substring)]]

我试图继承 QCompleter 类,但没有任何运气......这是我到目前为止所拥有的:

从 PySide 导入 QtCore、QtGui

class Completer(QtGui.QCompleter):
    def __init__(self,stringlist,parent=None):
        super(Completer,self).__init__(parent)
        self.stringlist = stringlist
        completeModel = QtGui.QStringListModel()
        completeModel.setStringList(stringlist)
        self.setModel(completeModel)
        self.activated[QtCore.QModelIndex].connect(self.activatedWrap)

    def activatedWrap(self, index):
        print(self.stringlist[index.row()])
        self.parent().setText(self.stringlist[index.row()])

    def popup(self):
        pop = super(Completer,self).popup()
        pop.setModel(QtGui.QStringListModel(self.stringlist))
        return pop


class AutoCompleteEdit(QtGui.QLineEdit):
    def __init__(self, stringlist, separator = ' ', addSpaceAfterCompleting = True):
        super(AutoCompleteEdit, self).__init__()
        self._separator = separator
        self.stringList = stringlist
        self._addSpaceAfterCompleting = addSpaceAfterCompleting
        self._completer = Completer(stringlist, self)
        self._completer.setModelSorting(QtGui.QCompleter.CaseInsensitivelySortedModel)

        self.setCompleter(self._completer)
        self._keysToIgnore = [QtCore.Qt.Key_Enter,
                              QtCore.Qt.Key_Return,
                              QtCore.Qt.Key_Escape,
                              QtCore.Qt.Key_Tab]


    def keyPressEvent(self, event):
        if self._completer.popup().isVisible():
            if event.key() in self._keysToIgnore:
                event.ignore()
                return
        text = self.text() + event.text()
        print(completionPrefix)
        self._completer.stringlist = [s for s in self.stringList if text in s]
        print(self._completer.stringlist)
        super(AutoCompleteEdit, self).keyPressEvent(event)

它部分工作......我很难解决的剩余问题是

  1. 列表项技巧“completionPrefix = self.text() + event.text()”对于获取 QLineEdit 在“super(AutoCompleteEdit, self).keyPressEvent(event )" 调用...它不适用于退格键、箭头键等...
  2. 列表项 使用“self.parent().setText(self.stringlist[index.row()])”调用在activatedWrap() 中设置的QLineEdit 的文本被QCompleter 覆盖(并设置为不正确的值) ...

可以说,整个方法不是很优雅,因为它只是试图修补 QCompleter 的行为,同时让它在后台找到自己的匹配项......但到目前为止我还没有找到更好的方法来解决这个问题!

4

0 回答 0