How to create a tree view (with a check box) inside a combo box - PyQt

I use PYQT to develop the application. my requirement is to insert a tree view with a checkbox inside the list items. I would like to know how to achieve this?

I have the following code, but this does not work.

class CheckboxInsideListbox(QWidget):
def __init__(self, parent = None):
    super(CheckboxInsideListbox, self).__init__(parent)
    self.setGeometry(250,250,300,300)
    self.MainUI()

def MainUI(self):
    #stb_label = QLabel("Select STB\'s")
    stb_combobox = QComboBox()

    length = 10
    cb_layout = QVBoxLayout(stb_combobox)
    for i in range(length):
        c = QCheckBox("STB %i" % i)
        cb_layout.addWidget(c)

    main_layout = QVBoxLayout()
    main_layout.addWidget(stb_combobox)
    main_layout.addLayout(cb_layout)



    self.setLayout(main_layout)

Please let me know if I missed something here.

0
source share
2 answers

You should create a model that supports Qt.CheckStateRole in the data methods and SetData and the Qt.ItemIsUserCheckable flag in the flags method.

I , , QSortFilterProxyModel , , , , PyQt (self.booleanSet self.readOnlySet).

def flags(self, index):
    if not index.isValid():
        return Qt.ItemIsEnabled

    if index.column() in self.booleanSet:
        return Qt.ItemIsUserCheckable | Qt.ItemIsSelectable | Qt.ItemIsEnabled
    elif index.column() in self.readOnlySet:
        return Qt.ItemIsSelectable | Qt.ItemIsEnabled
    else:
        return QSortFilterProxyModel.flags(self, index)

def data(self, index, role):
    if not index.isValid():
        return QVariant()

    if index.column() in self.booleanSet and role in (Qt.CheckStateRole, Qt.DisplayRole):
        if role == Qt.CheckStateRole:
            value = QVariant(Qt.Checked) if index.data(Qt.EditRole).toBool() else QVariant(Qt.Unchecked)
            return value
        else: #if role == Qt.DisplayRole:
            return QVariant()
    else:
        return QSortFilterProxyModel.data(self, index, role)

def setData(self, index, data, role):
    if not index.isValid():
        return False

    if index.column() in self.booleanSet and role == Qt.CheckStateRole:
        value = QVariant(True) if data.toInt()[0] == Qt.Checked else QVariant(False)
        return QSortFilterProxyModel.setData(self, index, value, Qt.EditRole)
    else:
        return QSortFilterProxyModel.setData(self, index, data, role)
0

, cb_layout. .

0

All Articles