【问题标题】:Preventing QComboboxView from autocollapsing when clicking on QTreeView item单击 QTreeView 项时防止 QComboboxView 自动折叠
【发布时间】:2018-10-05 18:59:04
【问题描述】:

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

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

【问题讨论】:

  • 根据您显示的图像,您只希望在单击项目 child2 时关闭弹出窗口,或者更确切地说是那些没有孩子的项目。我是对的?
  • @eyllanesc 没错。但即使我点击箭头,弹出窗口也会自动关闭

标签: python python-3.x pyqt pyqt5 qcombobox


【解决方案1】:

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

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_())

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

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_())

【讨论】:

  • 您的解决方案很棒,但它不允许选择父项。我希望能够选择父项,我的问题是当我单击箭头展开父项时,它会被选中
  • @SergeyMaslov 你必须清楚,所以我问你这个问题并指出,如果你想要没有孩子的项目只能选择,你说是的。
  • 对于这个误会我很抱歉。我把你的问题搞错了
  • @SergeyMaslov 你应该指出它只有在按下箭头时才可选择。
  • 是的。我需要能够同时选择父母和孩子,但当我单击箭头时不能。而这里的棘手之处在于覆盖箭头点击方法
猜你喜欢
  • 2013-10-03
  • 1970-01-01
  • 1970-01-01
  • 2010-11-28
  • 2020-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多