Adjust Indents In Qtablewidget Cells And Header Items
Solution 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:
classPaddingDelegate(QtWidgets.QStyledItemDelegate):def__init__(self, padding=1, parent=None):
super(PaddingDelegate, self).__init__(parent)
self._padding = ' ' * max(1, padding)
defdisplayText(self, text, locale):
returnself._padding + text
defcreateEditor(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)
Post a Comment for "Adjust Indents In Qtablewidget Cells And Header Items"