Remove unwanted padding/spacing in QTableWidget cells

Question:

I’ve created a QTableWidget and populated its last column with QPushButtons added inside a QButtonGroup (given in the code below):

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys

class ModTableWidget(QTableWidget):
    def __init__(self):
        super().__init__(0, 3)
        self.setHorizontalHeaderLabels(["Alias", "Path", ""])
        
        self.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
        self.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
        self.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents) 
        self.setSelectionBehavior(QAbstractItemView.SelectRows)

        self.is_default_group = QButtonGroup()

        for item in range(10):
            self.addItem(str(item), str(item))

    def addItem(self, alias, path):
        last_row_index = self.rowCount()
        self.insertRow(last_row_index)

        alias_item = QTableWidgetItem()
        alias_item.setText(alias)
        self.setItem(last_row_index, 0, alias_item)

        path_item = QTableWidgetItem()
        path_item.setText(path)
        self.setItem(last_row_index, 1, path_item)

        is_default_btn = QPushButton("Btn")
        is_default_btn.setMaximumWidth(30)
        is_default_btn.setCheckable(True)

        self.is_default_group.addButton(is_default_btn)
        self.setCellWidget(last_row_index, 2, is_default_btn)

if __name__ == '__main__':
    app = QApplication(sys.argv)

    tablewidget = ModTableWidget()
    tablewidget.show()

    sys.exit(app.exec_())

It is working fine, but it adds a little space on the last column:

enter image description here

I assume that it adds that little space by default, as it’s also noticeable on the images in this question. The most relevant question I found is this one, in which they talked about implementing custom painting through a delegate – though I’m not sure if this is the right path as I’m somewhat new to this concept.

Asked By: Eliazar

||

Answers:

It seems that this may be caused by the minimum section size of the horizontal header. This value partly depends on the current style and font, so it may differ between systems. On mine, it happens to be 30px, which coincidently matches the maximum width set on the buttons – so I don’t see a gap. Presumably on your system it must be slightly wider. Anyway, adjusting the value should hopefully fix the issue for you:

    print(self.horizontalHeader().minimumSectionSize())
    self.horizontalHeader().setMinimumSectionSize(30)
Answered By: ekhumoro