qtpysideqtreeviewqtreewidgetqtreewidgetitem

How can I set the alignment of the arrows on a QTreeWidgetItem


enter image description here

I want these TreeWidget Arrows to align with the top of the TreeWidgetItem.

I've got a QtWidgets.QTreeWidget(), and have created a custom QtWidgets.QTreeWidgetItem().

I then set a custom Item widget self.tree_widget.setItemWidget(self.tree_widget_item, 0, self.main_widget)

As a result the decorator / arrow positions itself evenly in the center of the geometry, however I want it to be aligned at the top.

I've been looking into setting the alignment for this, but am not 100% sure where to set it, or if I need to set it through a style sheet. If I'm unable to move this I can create a custom widget to replace the decorator, and hide the default ones, but I'd prefer to use what's here if possible. Any ideas? Thanks!


Solution

  • You could reimplement QTreeView.drawBranches and set a smaller height to the QRect used to draw each branch. Simply using the width is a good value if the arrows are symmetrical.

    import sys
    from PySide2.QtWidgets import *
    
    class Tree(QTreeWidget):
    
        def drawBranches(self, painter, rect, index):
            rect.setHeight(rect.width())
            super().drawBranches(painter, rect, index)
            
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        tree = Tree()
        for i in range(5):
            item = QTreeWidgetItem([f'Item {i}\n\n'])
            item.addChild(QTreeWidgetItem([f'Child {i}']))
            tree.addTopLevelItem(item)
        tree.show()
        sys.exit(app.exec_())
    

    Before    |    After:

    enter image description here      enter image description here