Skip to content Skip to sidebar Skip to footer

Preventing Qcomboboxview From Autocollapsing When Clicking On Qtreeview Item

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.

Solution 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 inrange(3):
        parent = model
        for j inrange(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_())

Post a Comment for "Preventing Qcomboboxview From Autocollapsing When Clicking On Qtreeview Item"