PySide在表格单元格中对齐文本?

时间:2017-10-16 14:32:39

标签: python pyside qtablewidget

我在QTDesigner中制作了一个QTable小部件。在我的代码中,我设置了表的属性,但我无法使文本对齐工作:

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)

1 个答案:

答案 0 :(得分:1)

您可以使用QTableWidgetItem setTextAlignment()方法更改每个项目的对齐方式:

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

但是如果要将对齐方式更改为所有项目,则必须使用委托:

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())