PySide 对齐 table 单元格中的文本?
PySide align text in a table cells?
我有一个用 QT Designer 制作的 QTablewidget。在我的代码中,我设置了 table 的属性,但我无法使文本对齐工作:
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)
您可以使用 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())
我有一个用 QT Designer 制作的 QTablewidget。在我的代码中,我设置了 table 的属性,但我无法使文本对齐工作:
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)
您可以使用 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())