kiryha
kiryha

Reputation: 193

PySide align text in a table cells?

I have a QTable widget made in QTDesigner. In my code I setup properties of the table but I cant get text alignment working:

def __init__(self):
    super(myClass, self).__init__()
    # SETUP UI
    self.setupUi(self)
    # Table setup
    self.myTable.verticalHeader().hide()  # Hide row numbers        
    self.myTable.setColumnCount(4)
    self.myTable.setHorizontalHeaderLabels(['A', 'B', 'C', 'D'])
    self.myTable.horizontalHeader().setResizeMode(QHeaderView.Stretch)
    # This code does not work:
    # self.myTable.setTextAlignment(Qt.AlignCenter|Qt.AlignVCenter)

Upvotes: 0

Views: 4931

Answers (1)

eyllanesc
eyllanesc

Reputation: 243965

You can change the alignment of each item using the QTableWidgetItem's setTextAlignment() method:

item = self.myTable.item(i, j)
item.setTextAlignment(QtCore.Qt.AlignCenter)

But if you want to change the alignment to all the items you must use a delegate:

class AlignDelegate(QtGui.QItemDelegate):
    def paint(self, painter, option, index):
        option.displayAlignment = QtCore.Qt.AlignCenter
        QtGui.QItemDelegate.paint(self, painter, option, index)

class MyClass(your_widget, your_design)
    def __init__(self):
        super(myClass, self).__init__()
        # SETUP UI
        self.setupUi(self)
        # Table setup
        self.myTable.verticalHeader().hide()  # Hide row numbers        
        self.myTable.setColumnCount(4)
        self.myTable.setHorizontalHeaderLabels(['A', 'B', 'C', 'D'])
        self.myTable.horizontalHeader().setResizeMode(QHeaderView.Stretch)
        self.myTable.setItemDelegate(AlignDelegate())

Upvotes: 1

Related Questions