4

If I have a QTableWidget, and I set the cell's column span using setSpan, Qt sizes the table as if the contents of the cell are entirely in the first column of the extended cell.

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

But is there a way to force Qt to account for the additional space made available by the spanned cell?

actual-v-desired-qtablewidget-span-sizing

buck54321
  • 847
  • 9
  • 21

1 Answers1

1

I had a lot of trouble with this, I couldn't get valid sizeHints for my table items and the QTableVeiew methods for getting item sizes seemed to be private in the Qt source. So this ruled out resizing the columns based on the width of individual items (i.e. ignoring / accounting for spanned items).

One workaround is to hide any row where there is spanned items causing an issue, resize to contents and then show them again. This requires you know what rows contained spanned items (for me this was easy because it is always the top row).

        self.setRowHidden(0, True)
        for col in range(self.columnCount()):
            self.resizeColumnToContents(col)
        self.setRowHidden(0, False)

where self is a QTableWidget

Joseph
  • 578
  • 3
  • 15