How to change background color after editing QTableView cell?

半腔热情 提交于 2019-12-01 19:27:56

You need to keep track of the edited items in the model somehow. You don't need UserRole. You can keep this internally, but of course, if you want to expose this information to the outside UserRole is perfect for this.

Here is a simple example. You can adjust this to your code:

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_())

QTableWidget has a signal itemChanged that needs to be connected to a slot. Once connected to a slot the signal will pass in the QTableWidgetItem that has been changed. From there you can use the methods for QTableWidgetItem such as setBackgroundColor to change the background.

Here's an example

#! /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_()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!