【问题标题】:PyQt4 QComboBox autocomplete without using setModel?PyQt4 QComboBox自动完成而不使用setModel?
【发布时间】:2015-03-10 02:16:34
【问题描述】:

我发现了几个具有自动完成功能的 PyQt4 QComboBox 的优秀示例(例如How do I Filter the PyQt QCombobox Items based on the text input?),但它们都使用 setModel 和 setSourceModel... 等。

是否可以在不使用模型的情况下在 PyQt4 中创建自动完成 QComboBox?

【问题讨论】:

  • 你试过使用 setCompleter 吗?
  • @smitkpatel,这行得通。

标签: autocomplete pyqt4 qcombobox


【解决方案1】:

使用 smitkpatel 的评论...我找到了一个有效的 setCompleter 示例。它是由 flutefreak 在QComboBox with autocompletion works in PyQt4 but not in PySide 发布的。

from PyQt4 import QtCore
from PyQt4 import QtGui

class AdvComboBox(QtGui.QComboBox):
    def __init__(self, parent=None):
        super(AdvComboBox, self).__init__(parent)

        self.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.setEditable(True)

        # add a filter model to filter matching items
        self.pFilterModel = QtGui.QSortFilterProxyModel(self)
        self.pFilterModel.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)
        self.pFilterModel.setSourceModel(self.model())

        # add a completer, which uses the filter model
        self.completer = QtGui.QCompleter(self.pFilterModel, self)
        # always show all (filtered) completions
        self.completer.setCompletionMode(QtGui.QCompleter.UnfilteredPopupCompletion)

        self.setCompleter(self.completer)

        # connect signals

        def filter(text):
            print "Edited: ", text, "type: ", type(text)
            self.pFilterModel.setFilterFixedString(str(text))

        self.lineEdit().textEdited[unicode].connect(filter)
        self.completer.activated.connect(self.on_completer_activated)

    # on selection of an item from the completer, select the corresponding item from combobox
    def on_completer_activated(self, text):
        if text:
            index = self.findText(str(text))
            self.setCurrentIndex(index)

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)

    combo = AdvComboBox()

    names = ['bob', 'fred', 'bobby', 'frederick', 'charles', 'charlie', 'rob']

    combo.addItems(names)
    combo.resize(300, 40)
    combo.show()

    sys.exit(app.exec_())

【讨论】:

    猜你喜欢
    • 2020-09-27
    • 2015-08-05
    • 1970-01-01
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多