El_Presidente
El_Presidente

Reputation: 63

Add and remove checkboxes for QTreeWidgetItems

My app is written with PyQt5. I have a QTreeWidget with some elements:

Parent
--Child 1
--Child 2

I want to add and remove checkboxes to child elements dynamically. I managed to add the checkboxes with

item.setFlags(item.flags() | 16)

and

item.setCheckState(0, QtCore.Qt.Checked)

But I have 2 problems:

I can't remove those checkboxes. I tried resetting the flags but the checkbox is still there, only disabled. I also cant use stylesheets because I cant .setStyleSheet for a single treeWidgetItem. How can I remove it?

and I don't want that.

Minimal example:

from PyQt5.QtWidgets import *

from PyQt5 import QtCore
app = QApplication([])
label = QTreeWidget()
label.show()
parent = QTreeWidgetItem(label)
parent.setText(0, "Parent")

child1 = QTreeWidgetItem(parent)
child1.setText(0, "child1")

child2 = QTreeWidgetItem(parent)
child2.setText(0, "child2")

child1.setFlags(child1.flags() | QtCore.Qt.ItemIsUserCheckable)
child1.setCheckState(0, QtCore.Qt.Checked)

child1.setFlags(child1.flags() & ~QtCore.Qt.ItemIsUserCheckable)


app.exec_()

Changing the ItemIsUserCheckable flag back doesn't remove the checkbox.

Upvotes: 1

Views: 2717

Answers (1)

eyllanesc
eyllanesc

Reputation: 243965

Do not place

item.setFlags(item.flags() | 16)

as it is not readable, it is better to use

item.setFlags(item.flags() | Qt.ItemIsUserCheckable)

Going to the problem, if you want to remove the checkbox then you have to remove that flag:

item.setFlags(item.flags() & ~Qt.ItemIsUserCheckable)
item.setData(0, QtCore.Qt.CheckStateRole, None)

The delegate to do the painting does not take into account the flag associated with the QModelIndex, so as @musicamante points out, the state must also be cleared by setting None.

Upvotes: 2

Related Questions