5

我有这个带有自定义模型和委托的 QTableView,我如何在编辑后更改单元格的背景颜色?

我应该在代表处这样做setModelData()吗?

index.model.setData(index, QVariant(True),Qt.UserRole) 

后来在模型的data()# 它调用自己?

if role == Qt.BackgroundColorRole:
    if index.model().data(index,Qt.UserRole).toBool():
        return QVariant(QColor(Qt.darkBlue))

在模型中,setData()我没有任何代码,例如:

if role==Qt.UserRole:
    ....

这样做的正确方法是什么?

编辑:这是我setData()在自定义模型中的整个方法

def setData(self, index, value, role=Qt.EditRole):

if index.isValid() and 0 <= index.row() < len(self.particles):
    particle = self.particles[index.row()]
    column = index.column()
    if column == ID:
        value,ok= value.toInt()
        if ok:
            particle.id =value                 
    elif column == CYCLEIDANDNAME:
        cycleId,cycleName= value.toString().split(' ')
        particle.cycleId =cycleId
#                also need to set cycleName
        for name in self.cycleNames:
            if name.endsWith(cycleName):
                particle.cycleFrameNormalized=particle.cycleName = name
                break

    elif column == CYCLEFRAME:
        value,ok= value.toInt()
        if ok:
            print 'set new val to :',value
            particle.cycleFrame =value 
#                    self.setData(index,QVariant(QColor(Qt.red)),Qt.BackgroundRole)

    elif column == CLASSID:
        value,ok= value.toInt()
        if ok:
            particle.classId =value                 
    elif column == VARIATIONID:
        value,ok= value.toInt()
        if ok:
            particle.variationId =value                 

    self.emit(SIGNAL("dataChanged(QModelIndex,QModelIndex)"),
              index, index)

    return True

return False

抱歉仍然没有线索,我将粘贴快速 gui 开发书示例中的完整代码:我在这里发布了我的代码 http://pastebin.com/ShgRRMcY

编辑单元格后如何更改代码以使单元格背景颜色发生变化?

4

2 回答 2

5

您需要以某种方式跟踪模型中已编辑的项目。你不需要UserRole。您可以将其保留在内部,但当然,如果您想将此信息公开给外部UserRole,则非常适合。

这是一个简单的例子。您可以将其调整为您的代码:

import sys
from PyQt4 import QtGui, QtCore

class Model(QtCore.QAbstractTableModel):
    def __init__(self, parent=None):
        super(Model, self).__init__(parent)

        # list of lists containing [data for cell, changed]
        self._data = [[['%d - %d' % (i, j), False] for j in range(10)] for i in range(10)]

    def rowCount(self, parent):
        return len(self._data)

    def columnCount(self, parent):
        return len(self._data[0])

    def flags(self, index):
        return QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable

    def data(self, index, role):
        if index.isValid():
            data, changed = self._data[index.row()][index.column()]

            if role in [QtCore.Qt.DisplayRole, QtCore.Qt.EditRole]:
                return data

            if role == QtCore.Qt.BackgroundRole and changed:
                return QtGui.QBrush(QtCore.Qt.darkBlue)

    def setData(self, index, value, role):
        if role == QtCore.Qt.EditRole:
            # set the new value with True `changed` status
            self._data[index.row()][index.column()] = [value.toString(), True]
            self.dataChanged.emit(index, index)
            return True
        return False

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    t = QtGui.QTableView()
    m = Model(t)
    t.setModel(m)
    t.show()

    sys.exit(app.exec_())
于 2012-12-18T07:44:05.103 回答
-2

QTableWidget有一个信号itemChanged需要连接到一个slot. 一旦连接到插槽,信号将通过QTableWidgetItem已更改的插槽。从那里您可以使用QTableWidgetItem诸如setBackgroundColor更改背景的方法。

这是一个例子

#! /usr/bin/env python2.7

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys


class Main(QTableWidget):

    def __init__(self):

        super(Main, self).__init__(2, 5)
        layout = QHBoxLayout(self)

        self.itemChanged.connect(self.changeBG)

    def changeBG(self, cell):

        cell.setBackgroundColor(QColor(225, 0, 225))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = Main()
    main.show()
    app.exec_()
于 2012-12-18T04:34:08.987 回答