0

相关问题中给出的解决方案消除了给定图像中显示的灰带。如果您按照以下脚本中的方式更改,则此灰色带将返回,并且单元格以垂直或水平方式固定。QtWidgets.QHeaderView.StretchQtWidgets.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 的原始代码可以在此处找到并在此处进行修改以显示问题。

4

1 回答 1

2

解决方案是创建一个 QHeaderView ,其中没有内容的部分被绘制:

class VerticalHeaderView(QtWidgets.QHeaderView):
    def __init__(self, parent=None):
        super().__init__(QtCore.Qt.Vertical, parent)

    def paintEvent(self, event):
        super().paintEvent(event)
        h = self.offset()
        for i in range(self.count()):
            h += self.sectionSize(i)
        if h < self.rect().bottom():
            r = QtCore.QRect(self.rect())
            r.moveTop(h)
            painter = QtGui.QPainter(self.viewport())
            painter.fillRect(r, QtGui.QColor("white"))
header = VerticalHeaderView(self.table)
self.table.setVerticalHeader(header)
于 2020-10-25T14:34:10.740 回答