Python PyQt5 tableView显示底片为红色和(x.xx)

Python PyQt5 tableView显示底片为红色和(x.xx),python,csv,tableview,pyqt5,Python,Csv,Tableview,Pyqt5,首先谢谢你试着帮助我。我在网上找到了一些代码,这些代码非常接近我所需要的功能,但最后一点我都做不到。我希望csv(tableView)中的任何负数显示为红色,格式为(x.xx),正数为x.xx。我在网上找到了一些关于更改单元格背景的代码,但是我想更改字体和使用抽象模型的示例,我需要用抽象而不是标准来完成所有这些吗?如果我需要把它抽象化,你能提供一个例子吗(我对这一切都很陌生) 要更改信息的显示格式,有几个选项: 重写模型的数据方法,以便它返回与标准角色相关联的必要值,例如在本例中为Qt::Di

首先谢谢你试着帮助我。我在网上找到了一些代码,这些代码非常接近我所需要的功能,但最后一点我都做不到。我希望csv(tableView)中的任何负数显示为红色,格式为(x.xx),正数为x.xx。我在网上找到了一些关于更改单元格背景的代码,但是我想更改字体和使用抽象模型的示例,我需要用抽象而不是标准来完成所有这些吗?如果我需要把它抽象化,你能提供一个例子吗(我对这一切都很陌生)


要更改信息的显示格式,有几个选项:

  • 重写模型的数据方法,以便它返回与标准角色相关联的必要值,例如在本例中为Qt::DisplayRole和Qt::ForegroundRole

  • 使用代理,如QIdentityProxyModel,或者通过覆盖数据方法作为前一个方法使用QSortFilterProxyModel,或者

  • 创建代理以自定义绘制

在本例中,我将使用最后一种方法,因为它更灵活,因为如果您希望在多个视图中以不同的形式显示模型的信息,并且您可以修改其他属性,这些属性不是由模型确定的,而是由其他元素(如样式)确定的

考虑到上述情况,解决方案是:

类CustomDelegate(qtwidts.QStyledItemDelegate):
def initStyleOption(self、option、index):
super(CustomDelegate,self).initStyleOption(option,index)
尝试:
值=浮点(option.text)
除值错误外:
返回
option.text=“{0:.2f}”。格式(值)
画笔=(
option.palete.brush(QtGui.qpalete.Text)
如果值>=0
else QtGui.QBrush(QtGui.QColor(“红色”))
)
option.palete.setBrush(QtGui.qpalete.Text,画笔)
self.tableView=qtwidts.QTableView(self)
# ...
委托=自定义委托(self.tableView)
self.tableView.setItemDelegateForColumn(1,委托)

简短回答:您必须对数据模型
QStandardItemModel
进行子类化,并修改
data
方法以返回适当的
qbrush
对象。见:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import csv
import locale

from PyQt5 import QtCore, QtGui, QtWidgets


class MyWindow(QtWidgets.QWidget):
    def __init__(self, fileName, parent=None):
        super(MyWindow, self).__init__(parent)

        locale.setlocale(locale.LC_ALL, '')

        self.fileName = fileName

        self.model = QtGui.QStandardItemModel(self)

        self.tableView = QtWidgets.QTableView(self)
        self.tableView.setModel(self.model)
        self.tableView.horizontalHeader().setStretchLastSection(True)

        self.pushButtonLoad = QtWidgets.QPushButton(self)
        self.pushButtonLoad.setText("Load Csv File!")
        self.pushButtonLoad.clicked.connect(self.on_pushButtonLoad_clicked)

        self.pushButtonWrite = QtWidgets.QPushButton(self)
        self.pushButtonWrite.setText("Write Csv File!")
        self.pushButtonWrite.clicked.connect(self.on_pushButtonWrite_clicked)

        self.layoutVertical = QtWidgets.QVBoxLayout(self)
        self.layoutVertical.addWidget(self.tableView)
        self.layoutVertical.addWidget(self.pushButtonLoad)
        self.layoutVertical.addWidget(self.pushButtonWrite)

    def loadCsv(self, fileName):
        with open(fileName, "r") as fileInput:
            # skip header
            next(fileInput)
            for row in csv.reader(fileInput):
                # convert to $x.xx and ($x.xx)
                row[-1] = float(row[-1])
                row[-1] = locale.currency(row[-1], grouping=True)

                items = [
                    QtGui.QStandardItem(field)
                    for field in row
                ]

                self.model.appendRow(items)

    def writeCsv(self, fileName):
        with open(fileName, "w", newline='') as fileOutput:
            writer = csv.writer(fileOutput)
            for rowNumber in range(self.model.rowCount()):
                fields = [
                    self.model.data(
                        self.model.index(rowNumber, columnNumber),
                        QtCore.Qt.DisplayRole
                    )
                    for columnNumber in range(self.model.columnCount())
                ]
                writer.writerow(fields)

    @QtCore.pyqtSlot()
    def on_pushButtonWrite_clicked(self):
        self.writeCsv(self.fileName)

    @QtCore.pyqtSlot()
    def on_pushButtonLoad_clicked(self):
        self.loadCsv(self.fileName)

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow("data.csv")
    main.show()

    sys.exit(app.exec_())