1

我有一个 QStandardItemModel 分配给 QTableView 我想根据模型的第 5 列的值更改每一行的颜色:

class MyStandardTableModel(QtGui.QStandardItemModel):
    def __init__(self, headerdata, parent=None, *args):
        QtGui.QStandardItemModel.__init__(self, parent, *args)
        self.headerdata = headerdata

    def data(self, index, role):
        if not index.isValid():
            return QtCore.QVariant()
        elif role != QtCore.Qt.DisplayRole:
            if role == QtCore.Qt.TextAlignmentRole:
                return QtCore.Qt.AlignHCenter
            if role == QtCore.Qt.BackgroundRole:
                status = index.sibling(index.row(), 5).data().toInt()[0]
                if status == 1:
                    return QtCore.QVariant(QtGui.QColor(QtCore.Qt.green))
                if status == 2:
                    return QtCore.QVariant(QtGui.QColor(QtCore.Qt.red))
        return QtGui.QStandardItemModel.data(self, index, role)

...

以及更改颜色的功能(仅用于测试的第 1 行和第 2 行):

def changeColor(self, model):
    model.setData(model.index(1, 5), 1)
    model.setData(model.index(2, 5), 2)

现在,当我调用函数时行不会立即changeColor改变,但是当我调用函数并滚动 QTableView 时会改变。

我想我必须发出一个信号,changeColor但我不知道是哪个。另外,也许它有适当的方法来做到这一点。

4

1 回答 1

1

Ok, found the solution.

The signal to be emitted is dataChanged(QModelIndex,QModelIndex). I thought it was emitted by the setData function but in fact not.

Changing the changeColor function by :

def changeColor(self, model):
    model.setData(model.index(1, 5), 1)
    model.setData(model.index(2, 5), 2)
    model.emit(QtCore.SIGNAL('dataChanged(QModelIndex,QModelIndex)'), model.index(1, 5), model.index(2, 5))

solves the problem.

于 2013-10-29T13:52:30.040 回答