python - 调整内容大小时,QTableWidget 尊重跨度

标签 python python-3.x pyqt pyqt5

如果我有一个 QTableWidget ,我使用 setSpan 设置单元格的列跨度, Qt 调整表格的大小,就好像单元格的内容完全在扩展单元格的第一列中一样。

from PyQt5 import QtWidgets, QtCore
import sys

class myMainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(myMainWindow, self).__init__()
        tableBoxWidget = QtWidgets.QWidget(self)
        tableBox = QtWidgets.QHBoxLayout(tableBoxWidget)
        self.setCentralWidget(tableBoxWidget)
        self.setMinimumWidth(750)
        tableBoxWidget.setContentsMargins(20,20,20,20)

        testTable = QtWidgets.QTableWidget(tableBoxWidget)
        tableBox.addWidget(testTable)

        testTable.setFocusPolicy(QtCore.Qt.NoFocus)
        testTable.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)

        testTable.setRowCount(3)
        testTable.setColumnCount(2)

        # setting column 1 resize to contents
        testTable.horizontalHeader().setStretchLastSection(False)
        testTable.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)

        longString = "abcdefghijklmnopqrstuvwxyz"
        shortString = "abc"

        #first row
        testTable.setItem(0, 0, QtWidgets.QTableWidgetItem(shortString))
        testTable.setItem(0, 1, QtWidgets.QTableWidgetItem(longString))

        #second row, two-column span
        testTable.setSpan(1, 0, 1, 2)
        testTable.setItem(1, 0, QtWidgets.QTableWidgetItem(longString))

        #third row, same as first
        testTable.setItem(2, 0, QtWidgets.QTableWidgetItem(shortString))
        testTable.setItem(2, 1, QtWidgets.QTableWidgetItem(longString))

        self.show()



app = QtWidgets.QApplication(sys.argv)
window = myMainWindow()
app.exec_()

但是有没有办法强制 Qt 考虑跨区单元提供的额外空间?

actual-v-desired-qtablewidget-span-sizing

最佳答案

我在这方面遇到了很多麻烦,我无法为我的表格项目获得有效的 sizeHints,并且用于获取项目大小的 QTableVeiew 方法在 Qt 源代码中似乎是私有(private)的。因此,这排除了根据单个项目的宽度调整列的大小(即忽略/考虑跨越项目)。
一种解决方法是隐藏跨项目导致问题的任何行,调整内容大小,然后再次显示它们。这要求您知道哪些行包含跨区项目(对我来说这很容易,因为它始终是第一行)。

        self.setRowHidden(0, True)
        for col in range(self.columnCount()):
            self.resizeColumnToContents(col)
        self.setRowHidden(0, False)
其中 self 是一个 QTableWidget

关于python - 调整内容大小时,QTableWidget 尊重跨度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52166539/

相关文章:

python - 使用变量访问 python 类中的函数

python - Qt - 暂时禁用所有事件或窗口功能?

Python - 仅使用循环删除空格

python - 如何在pylab(pyplot)中使用阶梯线(阶梯曲线)填充两种不同颜色的区域?

python - Boto3 中的异常 - botocore.exceptions.EndpointConnectionError

python 3.4 :ImportError: no module named win32api

python - Pyramid:用于自定义记录器和外部授权系统的 Tween 或 WSGI 中间件?

python-3.x - 如何在 AWS EMR 中将 Jupyter 笔记本设置为 Python3 而不是 Python2.7

python - QListWidget 所选项目按行排序

python - 单击按钮时如何调用两个函数?