The solution given at the related question removes the grey band show in the image given. If you change QtWidgets.QHeaderView.Stretch
into QtWidgets.QHeaderView.Fixed
as done in below script this grey band is back and cells are fixed in either vertical or horizontal manner.
What desired is removing the grey band without resizing cell height or width.
Note 1: original image is from user xwsz.
The code:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, data):
super(TableModel, self).__init__()
self._data = data
def data(self, index, role):
if role == Qt.DisplayRole:
return self._data[index.row()][index.column()]
def rowCount(self, index):
return len(self._data)
def columnCount(self, index):
return len(self._data[0])
def headerData(self, section, orientation, role):
# section is the index of the column/row.
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
column_label = ['A', 'B1', 'B2']
return column_label[section]
if orientation == Qt.Vertical:
row_label = ['Device', 'ID', 'Operation', 'Weigth', 'Row 5', 'No Show']
return row_label[section]
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.table = QtWidgets.QTableView()
data = [
[4, 9, 2],
[1, 0, 0],
[3, 5, 0],
[3, 3, 2],
[7, 8, 9],
]
self.model = TableModel(data)
# self.table.verticalHeader().setDefaultSectionSize(50) # does not sove it.
# self.table.verticalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
self.table.verticalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Fixed)
# self.table.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
self.table.setModel(self.model)
self.setCentralWidget(self.table)
app=QtWidgets.QApplication(sys.argv)
window=MainWindow()
window.show()
app.exec_()
Note 2: the original code from Martin Fitzpatrick can be found here and is modified here to show the issue.