调整 QTableWidget 单元格和标题项中的缩进 [英] Adjust indents in QTableWidget cells and header items

查看:220
本文介绍了调整 QTableWidget 单元格和标题项中的缩进的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在左侧的 QTableWidget 中对齐文本,但我还想添加一个缩进,这样文本就不会卡在边框上.在图像上,col_2 是我想要的.我希望标题标签也一样.

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

推荐答案

对于缩进,QSS 参考 建议应该可以使用 QTableWidget::itemQHeaderView::section 选择器:

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}
    """)

然而,我尝试了填充、边距和边框设置的所有各种组合,发现它们要么根本不起作用,要么有奇怪和丑陋的副作用.在查看关于 SO 和其他地方的几个类似问题之后,这些样式表设置的确切行为似乎取决于您所在的平台和/或您使用的小部件样式.希望它们对您来说可以正常工作,但如果您发现一些小故障,请不要感到惊讶.

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.

如果样式表解决方案不起作用,大多数人会使用自定义项目委托.这通常涉及重新实现 paint 方法.但是,另一种方法是重新实现 displayText 方法和 pad带空格的返回文本.这根本不会影响基础数据,并以更简单的方式提供完全等效的结果.重新实现 createEditor 方法也很简单编辑单元格时调整边距.完整的自定义 item-delegate 将如下所示:

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

它可以像这样使用:

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)

这篇关于调整 QTableWidget 单元格和标题项中的缩进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆