单击 QTreeView 项时防止 QComboboxView 自动折叠 [英] Preventing QComboboxView from autocollapsing when clicking on QTreeView item

查看:48
本文介绍了单击 QTreeView 项时防止 QComboboxView 自动折叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python3 + PyQt5.在我的程序中,我在该组合框中有 QCombobox 和 QTreeView.QCOmbobox 默认行为是在单击项目时隐藏下拉列表.但是,在我的情况下,它里面不是一个简单的列表,而是一个 TreeView.因此,当我单击其中的展开箭头时,QCombobox 会隐藏视图,因此我无法选择项目

I'm using python3 + PyQt5. In my program I have QCombobox and a QTreeView inside that combobox. The QCOmbobox default behavior is to hide the dropdown list when an item is clicked. However, in my case there is not a simple list inside it, but a TreeView. So when I'm clicking an Expand Arrow in it, QCombobox hides the view so I can not select an item

我这里没有任何具体代码,只是小部件初始化.我知道有信号和插槽,所以我的猜测是组合框捕获项目点击事件并将其包装在自己的行为中.所以我想我需要重写一些方法,但我不确定到底是哪个.

I have no any specific code here, just widget initialization. I know that there are signals and slots so my guess here is that combobox catches the item click event and wraps it in its own behavior. So I think I need to override some method but I'm not sure which exactly.

推荐答案

对于不想在 QComboBox 中设置的项目,您必须禁用该项目可选择的项目,例如:

You must disable the item being selectable to the items that you do not want to be set in the QComboBox, for example:

import sys

from PyQt5 import QtWidgets, QtGui


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = QtWidgets.QComboBox()
    model = QtGui.QStandardItemModel()
    for i in range(3):
        parent = model
        for j in range(3):
            it = QtGui.QStandardItem("parent {}-{}".format(i, j))
            if j != 2:
                it.setSelectable(False)
            parent.appendRow(it)
            parent = it
    w.setModel(model)

    view = QtWidgets.QTreeView()
    w.setView(view)
    w.show()
    sys.exit(app.exec_())

更优雅的解决方案是覆盖模型的标志:

A more elegant solution is to overwrite the flags of the model:

import sys

from PyQt5 import QtWidgets, QtGui, QtCore

class StandardItemModel(QtGui.QStandardItemModel):
    def flags(self, index):
        fl = QtGui.QStandardItemModel.flags(self, index)
        if self.hasChildren(index):
            fl &= ~QtCore.Qt.ItemIsSelectable
        return fl

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = QtWidgets.QComboBox()
    model = StandardItemModel()
    for i in range(3):
        parent = model
        for j in range(3):
            it = QtGui.QStandardItem("parent {}-{}".format(i, j))
            parent.appendRow(it)
            parent = it
    w.setModel(model)
    view = QtWidgets.QTreeView()
    w.setView(view)
    w.show()
    sys.exit(app.exec_())

这篇关于单击 QTreeView 项时防止 QComboboxView 自动折叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆