使用代理模型来更改值更改后的QTableView的单元格背景颜色

问题描述 投票:0回答:1

我有一个小写的QAbstractTableModel

其中包含无类型值以将行显示为空

class ViewModel(qtc.QAbstractTableModel):

    def __init__(self, input_data=None):
        super().__init__()

        self.input_data = input_data or [[None, None],[None, None]]

如果插入的值(替换无类型值)在/超出某个范围,我想更改单元格的颜色

例如z = 12 <= x <= 20

# False == red, True == green

仅当项目为eddit或self.model.layoutChanged.emit()被执行

更改QTableView的单元格背景颜色的答案表明更改数据方法How to change cell's background color of a QTableView [duplicate] 但这会在一开始就为细胞着色

我在QT论坛中发现了一种在视图和模型之间插入代理模型的方法How to simply change the background colour of a cell inside a TableView

我正在尝试将代码实施到Pyqt5中,到目前为止尚不完整。有没有我不知道的PyQt5方法吗?

示例代码

import sys
import re

from PyQt5 import QtWidgets as qtw
from PyQt5 import QtCore as qtc


class ViewModel(qtc.QAbstractTableModel):

    def __init__(self, input_data=None):
        super().__init__()

        self.input_data = input_data or [[None, None],[None, None]]



    def data(self, index, role):  # parameter index, role are needed !
        if role == qtc.Qt.DisplayRole:
            try:
                text = self.input_data[index.row()][index.column()]
            except IndexError:
                text = None

            return text

    def rowCount(self, index=qtc.QModelIndex()):
        return 0 if index.isValid() else len(self.input_data)


    def columnCount(self, index):
        return len(self.input_data[0])

    def headerData(self, section, orientation, role):
        # section is wich index of the orintation
        if role == qtc.Qt.DisplayRole:
            if orientation == qtc.Qt.Vertical:
                return "row"

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

    def setData(self, index, value, role=qtc.Qt.EditRole):
        if role == qtc.Qt.EditRole:
            try:
                row = index.row()
                column = index.column()

                pattern = '^[\d]+(?:,[\d]+)?$'


                if re.fullmatch(pattern, value, flags=0):
                    print("true")
                    self.input_data[row][column] = value  # float
                else:
                    print("nope")
                    pass

                return True

            except ValueError:
                print("not a number")
                return False


class MainWindow(qtw.QWidget):



    def __init__(self):
        super().__init__()

        # View
        table_view = qtw.QTableView()

        self.model = ViewModel()

        table_view.setModel(self.model)

        # size and position
        qtRectangle = self.frameGeometry()
        centerPoint = qtw.QDesktopWidget().availableGeometry().center()
        qtRectangle.moveCenter(centerPoint)
        self.move(qtRectangle.topLeft())
        # size
        self.resize(1000, 410)

        # layout
        qvboxlayout = qtw.QVBoxLayout()
        qvboxlayout.addWidget(table_view)

        self.setLayout(qvboxlayout)
        self.show()


if __name__ == '__main__':
    app = qtw.QApplication(sys.argv)
    w = MainWindow()
    sys.exit(app.exec_())

python pyqt pyqt5 qsortfilterproxymodel
1个回答
0
投票
如果要使用代理来更改颜色,则仅应覆盖data()方法:

class ColorProxy(qtc.QIdentityProxyModel): def data(self, index, role=qtc.Qt.DisplayRole): if role == qtc.Qt.BackgroundRole: data = index.data() try: value = float(data) except (ValueError, TypeError) as e: print("error:", e) else: return qtg.QColor("green") if 12 <= value <= 20 else qtg.QColor("red") return super().data(index, role)

# ...
self.model = ViewModel()

proxy = ColorProxy()
proxy.setSourceModel(self.model)

table_view.setModel(proxy)
# ...
© www.soinside.com 2019 - 2024. All rights reserved.