Reputation: 7889
I have a QTreeWidget with two levels. Parent level is first and child level underneath. I want the parent level to contain checkboxes, but I want the children to have no checkboxes. In the following example, every QTreeWidgetItem shows a checkbox. If I remove "child.setCheckState(0, Qt.Unchecked)" then ALL checkboxes disappear, not just the child checkboxes.
How can I hide the child checkboxes, but not the parent checkboxes?
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
def main():
app = QApplication (sys.argv)
tree = QTreeWidget ()
headerItem = QTreeWidgetItem()
item = QTreeWidgetItem()
for i in xrange(2):
parent = QTreeWidgetItem(tree)
parent.setText(0, "Parent {}".format(i))
parent.setFlags(parent.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable)
parent.setExpanded(True)
parent.setCheckState(0, Qt.Unchecked)
for x in xrange(3):
child = QTreeWidgetItem(parent)
child.setFlags(child.flags() & ~(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable))
child.setText(0, "Child {}".format(x))
#child.setCheckState(0, Qt.Unchecked)
tree.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Upvotes: 0
Views: 2263
Reputation: 12741
Here "child.setCheckState(0, Qt.Unchecked)" -- does mean that "you are setting checkbox to column "0" with unchecked state".
Now revisit your code:
you are not setting it for parent which you want so do something like below:
set checkbox for parent item:
parent.setCheckState(0, Qt.Unchecked)
Remove below code completely as it sets checkboxes for child which you do not want
child.setCheckState(0, Qt.Unchecked)
Also Delete the flags setting, as we noticed setting flags to parent, are carried to child items.
The code Roughly looks somewhat like this in first for loop:
parent = QTreeWidgetItem(tree)
parent.setText(0, "Parent {}".format(i))
parent.setExpanded(True)
parent.setCheckState(0, Qt.Unchecked)
for x in xrange(3):
child = QTreeWidgetItem(parent)
child.setText(0, "Child {}".format(x))
Upvotes: 1
Reputation: 11064
You should remove the the flag ItemIsUserChechable
and ItemIsSelectable
from your child flags instead of adding them:
child.setFlags(child.flags() & ~(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable))
I would also expect that you shouldn't set the checkState of the child, but that of the parent. See the python documentation for more information about binary operations.
Upvotes: 0