简体   繁体   中英

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++ :DI 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)

With PySide2 and a QTableview, this works:

self.table = QtWidgets.QTableWidget(5, 3, self)
self.table.horizontalHeader().setDefaultAlignment(QtCore.Qt.AlignRight)

I don't have a working PyQt5/QTreeView example to see if it is similar; but maybe this is enough to help you?

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.

If you want to set alignment for specific column:

column = 2
self.dataView.headerItem().setTextAlignment(column, QtCore.Qt.AlignCenter)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM