如何将列中的所有项目对齐到QTableWidget的中心

时间:2018-10-04 10:23:39

标签: python pyqt pyqt5 qtablewidget

我正在使用PyQt5和PyCharm。如何将一列下的所有单元格对齐到中心?下面的代码似乎可以正常工作,但仅适用于作为标头的一个单元格。我应该更改或添加什么?

item3 = QtWidgets.QTableWidgetItem('Item Name')
item3.setTextAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.tableWidget.setHorizontalHeaderItem(2, item3)

1 个答案:

答案 0 :(得分:1)

建立列对齐的一种简单方法是通过委托:

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