Preventing QComboboxView from autocollapsing when clicking on QTreeView item

百般思念 提交于 2020-01-16 01:19:10

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/50019909/preventing-qcomboboxview-from-autocollapsing-when-clicking-on-qtreeview-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!