如何将 PySide6 QTableWidget 列宽设置为 15pt?

How to set a PySide6 QTableWidget column width to 15pt?

我想创建一个 table 小部件,其中包含第 2 列中的按钮。按钮很细 (15pt),因为它们只包含一个 T。

这是一个小的工作示例。

import sys
from PySide6.QtWidgets import (
    QMainWindow, QApplication, QTableWidget, QLabel, QPushButton
)
from PySide6.QtCore import Qt

class MainWindow(QMainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle("My App")

        Nrows, Ncols = 5, 3
        table = QTableWidget(Nrows, Ncols, self)

        for col in [0, 2]:
            for row in range(Nrows):
                table.setCellWidget(row, col,
                    QLabel(f"row {row} column {col}")
                )
        for row in range(Nrows):
            push = QPushButton("T")
            push.setFixedWidth(15)
            table.setCellWidget(row, 1,push)

        self.setCentralWidget(table)

app = QApplication(sys.argv)
w = MainWindow()
w.show()
app.exec_()

这会产生以下 window。

问题是我希望按钮列在启动时也为 15pt。使列宽与按钮的宽度相同。

两个问题是:

  1. 我需要在启动时调整大小
  2. 调整大小不会下降到 15pt。看来列宽不能低于约。 20pt.

如何解决?

默认的最小部分大小由当前样式和字体计算得出。

您可以使用 setColumnWidth():

覆盖部分的大小
table.setColumnWidth(1, 15)

这与使用 header 的 resizeSection 相同:

table.horizontalHeader().resizeSection(1, 15)

但您还应确保设置了最小部分,否则如果用户尝试调整部分大小,它将回退到默认的最小值:

table.horizontalHeader().setMinimumSectionSize(15)

请注意,您也可以使用 setSectionResizeMode()(但您仍然必须设置最小部分大小):

table.horizontalHeader().setMinimumSectionSize(15)
table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeToContents)

请注意,15 的按钮宽度确实太窄了,您不能依赖您的计算机字体:其他用户可能有不同的样式(这会在文本和文本之间添加更大的边距)按钮边框)或比你的字体大;您应该确保最小宽度基于字体和样式,并且始终提供调整大小的可能性:

width = (
    self.fontMetrics().horizontalAdvance("T")
    + self.style().pixelMetric(QStyle.PM_ButtonMargin) * 2
    + self.style().pixelMetric(QStyle.PM_DefaultFrameWidth) * 2
)

for row in range(Nrows):
    push = QPushButton("T")
    push.setMinimumWidth(width) # set a *minimum* width, not a fixed one
    table.setCellWidget(row, 1, push)
table.horizontalHeader().setMinimumSectionSize(width)
table.setColumnWidth(1, width)