【发布时间】:2021-09-04 07:04:18
【问题描述】:
我正在尝试创建一个组合框小部件,它根据用户输入过滤值并突出显示它们。通过一些冲浪,我几乎可以完成它。该小部件能够从下拉列表中过滤值。但是,当我们在可编辑的 lineedit 中键入时不完全匹配时,它不会突出显示下拉列表中的第一个可用值。以下是代码
import sys, os
from PyQt5.Qt import Qt
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class ExtendedComboBox(QComboBox):
def __init__(self, parent=None):
super(ExtendedComboBox, self).__init__(parent)
self.setFocusPolicy(Qt.StrongFocus)
self.setEditable(True)
self.view().setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
# add a filter model to filter matching items
self.pFilterModel = QSortFilterProxyModel(self)
self.pFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive)
self.pFilterModel.setSourceModel(self.model())
# add a completer, which uses the filter model
self.completer = QCompleter(self.pFilterModel, self)
# always show all (filtered) completions
self.completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
self.setCompleter(self.completer)
# connect signals
self.lineEdit().textEdited.connect(self.pFilterModel.setFilterFixedString)
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(text)
self.setCurrentIndex(index)
self.activated[str].emit(self.itemText(index))
# on model change, update the models of the filter and completer as well
def setModel(self, model):
super(ExtendedComboBox, self).setModel(model)
self.pFilterModel.setSourceModel(model)
self.completer.setModel(self.pFilterModel)
# on model column change, update the model column of the filter and completer as well
def setModelColumn(self, column):
self.completer.setCompletionColumn(column)
self.pFilterModel.setFilterKeyColumn(column)
super(ExtendedComboBox, self).setModelColumn(column)
class Application(QWidget):
def __init__(self):
super().__init__()
items = set(
"You can use QCompleter to provide auto completions in any Qt widget, such as QLineEdit and QComboBox. When the user starts typing a word, QCompleter suggests possible ways of completing the word, based on a word list.".split(
' '))
layout = QVBoxLayout(self)
cb = ExtendedComboBox(self)
cb.addItems(items)
cb.setCurrentText("")
layout.addWidget(cb)
layout.addStretch(1)
if __name__ == "__main__":
app = QApplication(sys.argv)
diag = Application()
diag.show()
sys.exit(app.exec_())
运行此代码时,我们会看到以下窗口,当我输入“an”时,您会看到“and”被突出显示
当我们键入任何从开头不匹配的字母时,它不会突出显示。请参考下图
我希望在上述情况下突出显示“提供”。 任何建议都会有所帮助。
此外,为了区分大小写,如果大小写不匹配,也不会突出显示匹配项。
【问题讨论】:
-
你试过设置
self.completer.setFilterMode(Qt.MatchContains)吗? -
@Heike 试过了,但没用。