Why does QTableView have blank margins and how can I remove them?

Tags: , , ,



The following PyQt program produces a window containing a QTableView with a margin space to its bottom and right (but not top and left) – even though the main-window is told to adjust itself to its contents size:

![Result of program showing empty margin

I was expecting to see:

Window without margin

If I increase the size of the window from the original position, I see:

Increased window increases empty margin

What is the purpose of that region? Can it be eliminated? If so, how?

import sys

from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QVBoxLayout, QWidget, QApplication, QMainWindow, QTableView


class TableModel(QtCore.QAbstractTableModel):
    def __init__(self):
        super().__init__()

    def data(self, index, role=None):
        if role == Qt.DisplayRole:
            return 42

    def rowCount(self, index):
        return 3

    def columnCount(self, index):
        return 4


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.table = QTableView()

        self.model = TableModel()
        self.table.setModel(self.model)
        self.table.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)

        self.setCentralWidget(self.table)


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

Answer

The blank areas are normal and expected if you don’t specify how the elements of the table should be resized. There are many different configurations to suit different use-cases, so you may need to experiment a little to get the exact behaviour you want.

The initial margins along the right and bottom edges are there to allow for scrollbars. If you don’t want scrollbars, you can switch them off like this:

    self.table.setHorizontalScrollBarPolicy(
        QtCore.Qt.ScrollBarAlwaysOff)
    self.table.setVerticalScrollBarPolicy(
        QtCore.Qt.ScrollBarAlwaysOff)

However, the blank areas will still be there when the window is resized – but you can deal with that by setting the section resize mode, like this:

    self.table.horizontalHeader().setSectionResizeMode(
        QtWidgets.QHeaderView.Stretch)

    self.table.verticalHeader().setSectionResizeMode(
        QtWidgets.QHeaderView.Stretch)

This might result in an unexpected initial size for the window, so it may be advisable to set an appropriate default:

    self.resize(400, 200)

For further details, see the documentation for QTableView and QHeaderView.



Source: stackoverflow