Skip to content Skip to sidebar Skip to footer

QCompleter Supporting Multiple Items Like Stackoverflow Tag Field

Is there a way to make the QCompleter for pyside work more similar to how the Tag editor here on StackOverflow works? Where a user can type a word and then if there is a space it a

Solution 1:

You must implement a logic that gets the last string, this will be the word to make the filter in the QComplete through setCompletionPrefix():

class LineEdit(QtGui.QLineEdit):
    def __init__(self, *args, **kwargs):
        QtGui.QLineEdit.__init__(self, *args, **kwargs)
        self.multipleCompleter = None

    def keyPressEvent(self, event):
        QtGui.QLineEdit.keyPressEvent(self, event)
        if not self.multipleCompleter:
            return
        c = self.multipleCompleter
        if self.text() == "":
            return
        c.setCompletionPrefix(self.cursorWord(self.text()))
        if len(c.completionPrefix()) < 1:
            c.popup().hide()
            return
        c.complete()

    def cursorWord(self, sentence):
        p = sentence.rfind(" ")
        if p == -1:
            return sentence
        return sentence[p + 1:]

    def insertCompletion(self, text):
        p = self.text().rfind(" ")
        if p == -1:
            self.setText(text)
        else:
            self.setText(self.text()[:p+1]+ text)

    def setMultipleCompleter(self, completer):
        self.multipleCompleter = completer
        self.multipleCompleter.setWidget(self)
        completer.activated.connect(self.insertCompletion)


def main():
    app = QtGui.QApplication(sys.argv)
    w = LineEdit()
    completer = QtGui.QCompleter(["Animals", "Dogs", "Birds", "Cats", "Elephant", "Zebra"])
    completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
    w.setMultipleCompleter(completer)
    w.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

Post a Comment for "QCompleter Supporting Multiple Items Like Stackoverflow Tag Field"