本文介绍了QCompleter 自定义补全规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Qt4.6,我有一个带有 QCompleter 的 QComboBox.

I'm using Qt4.6 and I have a QComboBox with a QCompleter in it.

通常的功能是基于前缀提供完成提示(这些可以在下拉列表中而不是内联中 - 这是我的用法).例如,给定

The usual functionality is to provide completion hints (these can be in a dropdown rather than inline - which is my usage) based on a prefix. For example, given

chicken soup
chilli peppers
grilled chicken

输入 ch 将匹配 chicken soup辣椒 但不匹配 grilled chicken.

entering ch would match chicken soup and chilli peppers but not grilled chicken.

我想要的是能够输入 ch 并匹配所有这些,或者更具体地说,chicken 并匹配 chicken soup烤鸡.
我还希望能够将 chs 之类的标签分配给 chicken soup 以生成另一个匹配项,而不仅仅是文本内容.我可以处理算法但是,

What I want is to be able to enter ch and match all of them or, more specifically, chicken and match chicken soup and grilled chicken.
I also want to be able to assign a tag like chs to chicken soup to produce another match which is not just on the text's content. I can handle the algorithm but,

我需要覆盖 QCompleter 的哪些功能?
我不太确定我应该去哪里找...

Which of QCompleter's functions do I need to override?
I'm not really sure where I should be looking...

推荐答案

基于@j3frea 的建议,这里是一个工作示例(使用 PySide).看来每次调用 splitPath 时都需要设置模型(在 setModel 中设置一次代理不起作用).

Based on @j3frea suggestion, here is a working example (using PySide). It appears that the model needs to be set every time splitPath is called (setting the proxy once in setModel doesn't work).

combobox.setEditable(True)
combobox.setInsertPolicy(QComboBox.NoInsert)

class CustomQCompleter(QCompleter):
    def __init__(self, parent=None):
        super(CustomQCompleter, self).__init__(parent)
        self.local_completion_prefix = ""
        self.source_model = None

    def setModel(self, model):
        self.source_model = model
        super(CustomQCompleter, self).setModel(self.source_model)

    def updateModel(self):
        local_completion_prefix = self.local_completion_prefix
        class InnerProxyModel(QSortFilterProxyModel):
            def filterAcceptsRow(self, sourceRow, sourceParent):
                index0 = self.sourceModel().index(sourceRow, 0, sourceParent)
                return local_completion_prefix.lower() in self.sourceModel().data(index0).lower()
        proxy_model = InnerProxyModel()
        proxy_model.setSourceModel(self.source_model)
        super(CustomQCompleter, self).setModel(proxy_model)

    def splitPath(self, path):
        self.local_completion_prefix = path
        self.updateModel()
        return ""


completer = CustomQCompleter(combobox)
completer.setCompletionMode(QCompleter.PopupCompletion)
completer.setModel(combobox.model())

combobox.setCompleter(completer)

这篇关于QCompleter 自定义补全规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-25 07:55