5

I am using PyQt5 and using PyCharm. How can I align all cells under one column to center? The code below seems to be working but for only one cell which is the header. What should I change or add?

item3 = QtWidgets.QTableWidgetItem('Item Name')
item3.setTextAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.tableWidget.setHorizontalHeaderItem(2, item3)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241

1 Answers1

9

A simple way to establish the alignment of a column is through the delegates:

import sys
from PyQt5 import QtCore, QtWidgets


class AlignDelegate(QtWidgets.QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super(AlignDelegate, self).initStyleOption(option, index)
        option.displayAlignment = QtCore.Qt.AlignCenter


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.tableWidget = QtWidgets.QTableWidget(15, 6)
        self.setCentralWidget(self.tableWidget)

        for i in range(self.tableWidget.rowCount()):
            for j in range(self.tableWidget.columnCount()):
                it = QtWidgets.QTableWidgetItem("{}-{}".format(i, j))
                self.tableWidget.setItem(i, j, it)

        delegate = AlignDelegate(self.tableWidget)
        self.tableWidget.setItemDelegateForColumn(2, delegate)

        # for all columns:
        # self.tableWidget.setItemDelegate(delegate)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())

enter image description here

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • I tried your code and **it works**. However I wonder if there is a way to do it without creating `AlignDelegate` as in your example. – mak Sep 14 '21 at 05:06
  • 1
    @mak What's wrong with my solution? Without justification I will not spend time looking for another solution. – eyllanesc Sep 14 '21 at 05:07
  • I wondered if you knew if there is a way to write in one liner pseudocode like: `self.tableWidget.setItemDelegateForColumn(2, QStyledItemDelegate(displayAlignment=QtCore.Qt.AlignCenter))`. However I understand your point. Thank you for your response. – mak Sep 14 '21 at 07:03