Search code examples
pythonpyqt5qtreeview

How can I change alignment of header QTreeView PyQt5?


I want to change alignment of header of QTreeView to the center or right side.. I google it but the answers were only for C++ :D I didn't understand..

I want to change (TITLES) Header to center or right side look at this: https://imgur.com/Jvfdcgn

Thank for help.

class My(QWidget,myui):

    def __init__(self,parent=None):
        super(QWidget,self).__init__(parent)
        self.setupUi(self)

        self.dataView=QTreeView()
        self.model=self.createModel(self)
        self.dataView.setModel(self.model)


    def information(self,name):
        self.addData(self.model,name)

    def createModel(self,parent):
        model=QStandardItemModel(0,1,parent)
        model.setHeaderData(self.TITLE,Qt.Horizontal,'TITLES') # I want to change 'TITLES' to the center or right side.

        return model

    def addData(self,model,TITLE):
        model.insertRow(0)
        model.setData(model.index(0,self.TITLE),TITLE)

Solution

  • You have to set the default alignment of the header.
    A QTableView or QTableWidget have both an horizontalHeader() and verticalHeader(), but since a QTreeView/QTreeWidget only has the horizontal header, the function is simply header().

    self.dataView.header().setDefaultAlignment(Qt.AlignRight|Qt.AlignVCenter)
    

    The vertical alignment is not usually necessary, I've just added it for completeness.