python GUI自动完成键值

时间:2019-03-03 03:17:57

标签: python pyqt pyqt5 qlineedit qcompleter

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

是否可以编辑链接中的代码,以便启用此功能?谢谢!

1 个答案:

答案 0 :(得分: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_())