如何获取QTableView的列宽

How to get QTableView column width

下面的代码创建一个 QTableView 链接到 QAbstractTableModel 三列:

为了给最后一列中的项目分配水平的红蓝渐变,我使用

创建了一个渐变

gradient = QtGui.QLinearGradient(0, 0, COLUMN_WIDTH, 0)

为了将渐变分成两半(一个涂成红色,另一个涂成蓝色)我需要提供 QLinearGradient 具有准确的 COLUMN_WIDTH 值。

如何获得COLUMN_WIDTH

from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])

class Model(QtCore.QAbstractTableModel):
    def __init__(self, parent=None):
        super(Model, self).__init__(parent)
        self.items = [['Row%s Col%s'%(row,col) for col in range(3)] for row in range(5)]

    def rowCount(self, parent=None):
        return len(self.items)

    def columnCount(self, parent=None):
        return len(self.items[0])

    def data(self, index, role=QtCore.Qt.DisplayRole):
        row = index.row()
        column = index.column()

        if role == QtCore.Qt.DisplayRole:
            if 0 <= row < self.rowCount() and 0 <= column < self.columnCount():
                return self.items[row][column]

        if role == QtCore.Qt.BackgroundRole and column==2:
            COLUMN_WIDTH = 50

            gradient = QtGui.QLinearGradient(0, 0, COLUMN_WIDTH, 0)
            gradient.setColorAt(0.5, QtGui.QColor('red'))
            gradient.setColorAt(0.5001, QtGui.QColor('blue'))
            brush = QtGui.QBrush(gradient)
            return brush

view = QtGui.QTableView()
model = Model(view)
view.setModel(model)
view.show()
app.exec_()

columnWidth()QTableView 的 属性:

COLUMN_WIDTH = self.parent().columnWidth(index.column())