【问题标题】:python GUI autocomplete by key valuepython GUI按键值自动完成
【发布时间】:2019-03-03 03:17:57
【问题描述】:

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

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

【问题讨论】:

  • 您的解释有点混乱,使用您建议的字典 1)如果在 QLineEdit 中您写 "Geo" 弹出窗口应该显示什么:不应该显示任何内容,显示 "Washington""Bush"或显示"George Washington""George Bush"? 2)如果选择了一个项目,QLineEdit中应该显示什么:"Geo" + item"George" + item
  • @eyllanesc 很抱歉让您感到困惑。当我开始输入“G”时,我希望它显示“Washington”和“Bush”。选择“华盛顿”时,我希望显示“华盛顿”。感谢您的澄清建议。我会更新问题。
  • 好的,我还有一个问题:{George: Washington, George: Bush} 不是有效的字典。条目可以是{"George": ["Washington", "Bush"]}吗?另外,您使用的是 PyQt4 还是 PyQt5?
  • 你是对的。该值将是一个列表。我猜是 PyQt5,但我是 PyQt 的新手,老实说,我不确定该选择哪个。
  • 好的。你知道我如何使用 PyQt5 @eyllanesc 解决这个问题吗?

标签: python pyqt pyqt5 qlineedit qcompleter


【解决方案1】:

您必须重写 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_())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    • 2018-02-03
    • 2019-03-02
    • 1970-01-01
    • 2017-08-07
    • 1970-01-01
    • 2012-03-14
    相关资源
    最近更新 更多