PyQt的 - 把颜色在QTableView中与现有数据(pyqt - put color in a

2019-10-17 22:15发布

我需要帮助上色我QTableView中。 @rainer帮我把颜色,当我初始化表,但现在,我已经有数据(但没有颜色//我的数据是在我的桌子开了CSV)的表,我想创建,当点击它的按钮颜色的tableview在某些行中,当存在与-2(数据)的行,这将是与颜色蓝色像.. - 我有一个按钮和一个表格。 此按钮CSV数据加载到我的tableview。 我想有一个新的按钮,该颜色该表中的行。 (但只颜色具有数据的-2,例如行)有些代码:

    self.fileName = (_fromUtf8('tweets.csv'))
    self.tableView = QTableView(self.tabSentimento)
    self.tableView.setGeometry(QRect(550,10,510,700))
    self.tableView.setObjectName(_fromUtf8("TabelaSentimento"))
    self.tableView.setModel(self.model)
    self.tableView.horizontalHeader().setStretchLastSection(True)

    self.pushButtonLoad = QPushButton(self.tabSentimento)
    self.pushButtonLoad.setGeometry(QRect(550,720,130,30))
    self.pushButtonLoad.setObjectName(_fromUtf8("buttonLoadCSV"))
    self.pushButtonLoad.setText(QApplication.translate("Form", "Process!", None, QApplication.UnicodeUTF8))
    self.pushButtonLoad.setStyleSheet('color:red;background-color:rgb(255, 255, 153);border:1px solid purple;')
    self.pushButtonLoad.clicked.connect(self.on_pushButtonLoad_clicked)


    def loadCsv(self, fileName):
        with open(fileName, "rb") as fileInput:
            for row in csv.reader(fileInput):    
                items = [
                    QStandardItem(field)
                    for field in row
            ]
                self.model.appendRow(items)

    def on_pushButtonLoad_clicked(self):
        print self.fileName
        self.loadCsv(self.fileName)

Answer 1:

例如,您可以继承模型,并重新实现data方法,该代码示例将单元格背景颜色变为蓝色,如果pushButtonColorize检查和单元格的值等于1,这也将影响细胞同排。

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)

import random
from PyQt4 import QtGui, QtCore

class MyStandardItemModel(QtGui.QStandardItemModel):
    _colorize = False
    def __init__(self, parent=None):
        super(MyStandardItemModel, self).__init__(parent)

    def setColorized(self, state):
        self._colorize = state

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if role == QtCore.Qt.BackgroundColorRole \
        and not self._colorize:
            return QtGui.QBrush()

        return super(MyStandardItemModel, self).data(index, role)

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

        self.pushButtonColorize = QtGui.QPushButton(self)
        self.pushButtonColorize.setText("Colorize Cells!")
        self.pushButtonColorize.setCheckable(True)
        self.pushButtonColorize.toggled.connect(self.on_pushButtonColorize_toggled)

        self.pushButtonReload = QtGui.QPushButton(self)
        self.pushButtonReload.setText("Reload Data!")
        self.pushButtonReload.clicked.connect(self.on_pushButtonReload_clicked)

        self.modelSource = MyStandardItemModel(self)

        self.tableView = QtGui.QTableView(self)
        self.tableView.horizontalHeader().setStretchLastSection(True)
        self.tableView.setModel(self.modelSource)

        self.layoutVertical = QtGui.QVBoxLayout(self)
        self.layoutVertical.addWidget(self.pushButtonReload)
        self.layoutVertical.addWidget(self.pushButtonColorize)
        self.layoutVertical.addWidget(self.tableView)

        self.pushButtonReload.click()

    @QtCore.pyqtSlot()
    def on_pushButtonReload_clicked(self):
        self.modelSource.clear()

        for rowNumber in range(3):
            items = []
            for columnNumber in range(3):
                item = QtGui.QStandardItem()
                item.setText(str(random.getrandbits(1)))

                items.append(item)

            self.modelSource.appendRow(items)

        if self.pushButtonColorize.isChecked():
            self.on_pushButtonColorize_toggled(True)

    @QtCore.pyqtSlot(bool)
    def on_pushButtonColorize_toggled(self, state):
        self.modelSource.setColorized(state)

        rowCount    = self.modelSource.rowCount()
        columnCount = self.modelSource.columnCount()

        for rowNumber in range(rowCount):
            for columnNumber in range(columnCount):
                cellIndex = self.modelSource.index(rowNumber, columnNumber)
                cellData  = self.modelSource.data(cellIndex, QtCore.Qt.DisplayRole)

                if str(cellData).isdigit() \
                and int(cellData) == 1:
                    for cellColumn in range(columnCount):
                        self.modelSource.setData(
                            self.modelSource.index(rowNumber, cellColumn),
                            QtGui.QColor(QtCore.Qt.blue),
                            QtCore.Qt.BackgroundColorRole
                        )

        self.modelSource.endResetModel()

if __name__ == "__main__":
    import sys

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

    main = MyWindow()
    main.resize(333, 222)
    main.show()

    sys.exit(app.exec_())


文章来源: pyqt - put color in a QTableView with existing data