相关问题中给出的解决方案消除了给定图像中显示的灰带。如果您按照以下脚本中的方式更改,则此灰色带将返回,并且单元格以垂直或水平方式固定。QtWidgets.QHeaderView.Stretch
QtWidgets.QHeaderView.Fixed
需要的是在不调整单元格高度或宽度的情况下移除灰色带。
注 1:原始图像来自用户xwsz。
编码:
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_()
注意 2:Martin Fitzpatrick 的原始代码可以在此处找到,并在此处进行修改以显示问题。