2

我正在尝试在 python 中创建一个自动完成 GUI,这样当我输入名字时,我会看到可能的姓氏。例如,假设我有这本字典:{"George": ["Washington", "Bush"]}. 当我开始输入“G”时,我希望它显示“Washington”和“Bush”。选择“华盛顿”时,我希望显示“华盛顿”。我是 GUI 新手,我认为 PyQt 有一个自动完成的例子,但是这些单词不是键值对而是单词列表。 https://wiki.python.org/moin/PyQt/Adding%20auto-completion%20to%20a%20QLineEdit

有没有办法编辑链接中的代码,以便我可以启用此功能?谢谢!

4

1 回答 1

0

您必须重写 pathFromIndex 方法,以便当您选择一些文本时,在 QLineEdit 中写入适当的选项,并且要更改弹出窗口中显示的内容,应使用委托。

from PyQt5 import QtCore, QtGui, QtWidgets

def create_model(d):
    model = QtGui.QStandardItemModel()
    for key, value in d.items():
        for val in value:
            it = QtGui.QStandardItem(key)
            it.setData(val, QtCore.Qt.UserRole)
            model.appendRow(it)
    return model

class StyledItemDelegate(QtWidgets.QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super(StyledItemDelegate, self).initStyleOption(option, index)
        option.text = index.data(QtCore.Qt.UserRole)

class Completer(QtWidgets.QCompleter):
    def __init__(self, parent=None):
        super(Completer, self).__init__(parent)
        QtCore.QTimer.singleShot(0, self.change_delegate)

    @QtCore.pyqtSlot()
    def change_delegate(self):
        delegate = StyledItemDelegate(self)
        self.popup().setItemDelegate(delegate)

    def pathFromIndex(self, index):
        return index.data(QtCore.Qt.UserRole)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    d = {
        "George": ["Washington", "Bush"],
        "Languages": ["Python", "C++"]
    }
    model = create_model(d)
    w = QtWidgets.QLineEdit()
    completer = Completer(w)
    completer.setModel(model)
    w.setCompleter(completer)
    w.show()
    sys.exit(app.exec_())
于 2019-03-03T06:24:53.787 回答