Set PyQT Table Header Text Align Left, Center and Right: A Beginner Guide – PyQT Tutorial

By | December 12, 2019

If you have created a table using pyqt, you may find the text in table header is centered. How to set the text align left, center and right? We will discuss this topic in this tutorial.

Create a table in pyqt

To set the text alignment in table header, we should create a table first. We can refer to this tutorial to know how to create a table in pyqt.

PyQT Add and Show a Table: A Beginner Guide – PyQT Tutorial

Set the text alignment in table header

After we have created a table, we can set the text alignment in its header.

First, we should import some libraries

from PyQt5 import QtCore

Set text align left

table.setHorizontalHeaderLabels(['id','Name','Age','Sex','Address'])
table.horizontalHeader().setDefaultAlignment(QtCore.Qt.AlignLeft)

In code above, we set the text in table header, then we set the text align left by setDefaultAlignment() function.

The effect of left alignment is:

pyqt table header text align left

Set text align center

table.horizontalHeader().setDefaultAlignment(QtCore.Qt.AlignCenter)

The effect is:

pyqt table header text align center

Set text align right

table.horizontalHeader().setDefaultAlignment(QtCore.Qt.AlignRight)

The effect is:

pyqt table header text align right

Leave a Reply