I have this QTreeWidget that I would like to be expanded by default.
I have read this same question many times but the solutions aren't working for me. I tried the commands for the root of my tree:
.ExpandAll()
and .itemsExpandable()
and for the children .setExpanded(True)
with no success.
Here is the code of my test application:
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget,
QTreeWidget, QTreeWidgetItem, QVBoxLayout
)
# ----------------------------------------------------------------
unsorted_data = [
['att_0', 'a', 2020],
['att_0', 'a', 2015],
['att_2', 'b', 5300],
['att_0', 'a', 2100],
['att_1', 'b', 5013],
['att_1', 'c', 6500],
]
# Sort data
list_att = []
for elem in range(len(unsorted_data)) :
att_ = unsorted_data[elem][0]
if att_ not in list_att:
list_att.append(att_)
list_att.sort()
n_att = len(list_att)
data = ['']*n_att
tree = ['']*n_att
list_a_number = []
list_b_number = []
list_c_number = []
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("My App")
widget = QWidget()
layout = QVBoxLayout()
widget.setLayout(layout)
# QTreeWidget
main_tree = QTreeWidget()
main_tree.setHeaderLabel('Test')
# main_tree.itemsExpandable() # NOT WORKING
# main_tree.expandAll() # NOT WORKING
sublevel_1 = []
for i, att in enumerate(list_att) :
list_a_number.clear()
list_b_number.clear()
list_c_number.clear()
# Create a dictionary
for elem in range(len(unsorted_data)) :
if unsorted_data[elem][0] == att :
if unsorted_data[elem][1]== 'a' :
list_a_number.append(str(unsorted_data[elem][2]))
if unsorted_data[elem][1] == 'b' :
list_b_number.append(str(unsorted_data[elem][2]))
if unsorted_data[elem][1] == 'c' :
list_c_number.append(str(unsorted_data[elem][2]))
data[i] = {'a' : list_a_number, 'b' : list_b_number, 'c' : list_c_number}
# Fill the Tree
items = []
att_id = list_att[i].split('\\')[-1]
tree[i] = QTreeWidgetItem([att_id])
tree[i].setExpanded(True) # NOT WORKING
sublevel_1.append(tree[i])
for key, values in data[i].items():
item = QTreeWidgetItem([key])
item.setCheckState(0, Qt.Checked)
tree[i].addChild(item)
for value in values :
child = QTreeWidgetItem([value])
child.setExpanded(True) # NOT WORKING
child.setCheckState(0, Qt.Checked)
item.addChild(child)
items.append(item)
main_tree.insertTopLevelItems(0, sublevel_1)
layout.addWidget(main_tree)
self.setCentralWidget(widget)
# ------------------------------------------------------------------
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
CodePudding user response:
Try expandAll
:
child.expandAll()
CodePudding user response:
You have to use expandAll after placing all the items in the QTreeWidget:
main_tree.insertTopLevelItems(0, sublevel_1)
main_tree.expandAll()
layout.addWidget(main_tree)
Note: One of the errors in your case is that you invoke setExpanded
before the item is added to the QTreeWidget. remove useless setExpanded