0

I'm running against a wall with Python and PyQt6. I'm simply trying to align each QTreeWidgetItem to the left. This works by default fine for the second column, but for some reason it refuses to align the first column's items to the left.

Here's my full code, it would be great if somebody could let me know why this isn't working:

import sys
from PyQt6.QtWidgets import QDialog, QTreeWidget, QTreeWidgetItem, QApplication
from PyQt6.QtCore import Qt

if __name__ == "__main__":
    app = QApplication(sys.argv)

    # Create the QDialog
    dialog = QDialog()
    dialog.setMinimumSize(200, 200)

    # Create the QTreeWidget
    tree = QTreeWidget(dialog)
    tree.setColumnCount(2)
    tree.setHeaderLabels(["age", "name"])

    # Add some data to the QTreeWidget
    data = [("20", "Alice"), ("25", "Bob"), ("30", "Eve")]
    for age, name in data:
        item = QTreeWidgetItem([age, name])
        item.setTextAlignment(0, Qt.AlignmentFlag.AlignLeft)
        tree.addTopLevelItem(item)

    tree.headerItem().setTextAlignment(0, Qt.AlignmentFlag.AlignLeft)

    # Show the QDialog
    dialog.show()

    app.exec()

Here's my output when I run this program:

enter image description here

I experimented with 2 ways of doing this, both being ignored:

item.setData(0, Qt.ItemDataRole.TextAlignmentRole, Qt.AlignmentFlag.AlignLeft)

item.setTextAlignment(0, Qt.AlignmentFlag.AlignLeft)

starball
  • 20,030
  • 7
  • 43
  • 238
Manuel
  • 11
  • 3
  • See [`setRootIsDecorated()`](https://doc.qt.io/qt-6/qtreeview.html#rootIsDecorated-prop) and [`setIndentation()`](https://doc.qt.io/qt-5/qtreeview.html#indentation-prop). Also please be careful when creating and editing posts, and ensure that the code is properly (and fully!) displayed by checking the post preview before submitting: if you use "code fences" (the three "ticks": \`\`\` ) they must be in a separate line. – musicamante Jan 06 '23 at 01:43

0 Answers0