pyqt - 将颜色放入带有现有数据的 QTableView [英] pyqt - put color in a QTableView with existing data

查看:63
本文介绍了pyqt - 将颜色放入带有现有数据的 QTableView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助为我的 QTableView 着色.@rainer 帮助我在初始化表格时添加颜色,但是现在,我已经有一个包含数据的表格(但没有颜色//我的数据是在我的表格中打开的 csv),我想创建一个按钮,单击它在某些行中为 tableview 着色,例如当有一行带有 -2(数据)时,它将是蓝色的颜色..-- 我有一个按钮和一张桌子.此按钮将 csv 数据加载到我的 tableview 中.我想要一个新按钮来为这个表格的行着色.(但例如,仅为具有 -2 数据的行着色)一些代码:

i need help to color my QTableView. @rainer helped me putting color when i initialize a table, but now, i already have a table with data(but without color// my data is a csv opened in my table), and i want to create a button that when clicked it colors the tableview in some lines, like when there is a row with -2 (data), it will be color with blue color.. -- I have a button and a table. This button load the csv data into my tableview. I want to have a new button that color the rows of this table. ( but color only rows that have -2 of data, for example) Some codes:

    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)

推荐答案

例如,您可以将模型子类化并重新实现 data 方法,此代码示例会将单元格背景颜色更改为蓝色,如果pushButtonColorize 被选中,单元格的值等于1.它也会影响同一行的单元格.

You could for example subclass the model and reimplement the data method, this code example will change the cells background color to blue if the pushButtonColorize is checked and the value of the cell is equal to 1. It will also affect cells in the same row.

#!/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 - 将颜色放入带有现有数据的 QTableView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆