问题
I would like to align texts in a QTableWidget
on the left side, but I would also like to add an indent so the text isn't stuck against the border. On the image, col_2
is what I want. And I would like the same for the header labels.
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QTableWidgetItem
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(400, 300)
self.gridLayout = QtWidgets.QGridLayout(Form)
self.gridLayout.setObjectName("gridLayout")
self.tableWidget = QtWidgets.QTableWidget(Form)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(0)
self.tableWidget.setRowCount(0)
self.gridLayout.addWidget(self.tableWidget, 0, 0, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
self.tableWidget.setRowCount(0)
self.tableWidget.setColumnCount(2)
entries = ['aa','bb','cc','dd','ee']
for row, form in enumerate(entries):
self.tableWidget.insertRow(row)
for column, item in enumerate(form):
self.tableWidget.setItem(row, column, QTableWidgetItem(str(item)))
self.tableWidget.setHorizontalHeaderLabels(['col_1', 'col_2'])
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
回答1:
For the indents, the QSS Reference suggests that it should be possible to use the QTableWidget::item and QHeaderView::section selectors:
self.tableWidget.setStyleSheet("""
QTableWidget::item {padding-left: 5px; border: 0px}
""")
self.tableWidget.horizontalHeader().setStyleSheet("""
QHeaderView::section {padding-left: 5px; border: 0px}
""")
However, I tried all the various combinations of padding, margin and border settings, and found that they either don't work at all, or have weird and ugly side-effects. After looking at several similar questions on SO and elsewhere, it seems that the exact behaviour of these stylesheet settings depends on what plaform you are on and/or what widget-style you are using. Hopefully they will work okay for you, but don't be surprised if you find a few glitches.
If the stylesheet solution doesn't work out, most people use a custom item-delegate. This usually involves reimplementing the paint method. However, an alternative approach would be to reimplement the displayText method and pad the returned text with spaces. This does not affect the underlying data at all, and gives completely equivalent results in a much simpler way. It is also quite simple to reimplement the createEditor method so that the left margin is adjusted when editing cells. The complete custom item-delegate would then look like this:
class PaddingDelegate(QtWidgets.QStyledItemDelegate):
def __init__(self, padding=1, parent=None):
super(PaddingDelegate, self).__init__(parent)
self._padding = ' ' * max(1, padding)
def displayText(self, text, locale):
return self._padding + text
def createEditor(self, parent, option, index):
editor = super().createEditor(parent, option, index)
margins = editor.textMargins()
padding = editor.fontMetrics().width(self._padding) + 1
margins.setLeft(margins.left() + padding)
editor.setTextMargins(margins)
return editor
and it can be used like this:
self.delegate = PaddingDelegate()
self.tableWidget.setItemDelegate(self.delegate)
The final piece of the puzzle is the indent for the header items. For this, it would seem simplest to just add some spaces to the label text:
self.tableWidget.setHorizontalHeaderLabels([' col_1', ' col_2'])
And the alignment of the header labels can be set like this:
self.tableWidget.horizontalHeader().setDefaultAlignment(
QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
来源:https://stackoverflow.com/questions/46750178/adjust-indents-in-qtablewidget-cells-and-header-items