如何控制QTableView Items的背景色 [英] How to control QTableView Items Background color

查看:41
本文介绍了如何控制QTableView Items的背景色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

源模型的data()将`QTableView的每个索引背景颜色设置为如果索引的行号是偶数则为绿色,如果是奇数则为蓝色.

It is the source model's data() that sets each of `QTableView's indexes background colors to a green if the index's row number is even and to a blue if it is odd.

然后代理模型过滤掉每三个索引.所以结果颜色都是无序的.

Then the Proxy model filters out every third index. So the resulted colors are all unordered.

问题是在索引被代理模型过滤之前在源模型中分配了背景颜色.

The problem is that the background colors are assigned in a Source Model before the Indexes get filtered by the Proxy model.

这是源代码:

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

class MyTableModel(QAbstractTableModel):
    def __init__(self, parent=None, *args):
        QAbstractTableModel.__init__(self, parent, *args)
        self.items = [i for i in range(90)]

    def rowCount(self, parent):
        return len(self.items)       
    def columnCount(self, parent):
        return 1

    def data(self, index, role):
        if not index.isValid():
            return QVariant()

        row=index.row()
        column=index.column()

        if role == Qt.DisplayRole:
            if row<len(self.items):
                return QVariant(self.items[row])
            else:
                return QVariant()

        if role==Qt.BackgroundColorRole:
            if row%2: bgColor=QColor(Qt.green)
            else: bgColor=QColor(Qt.blue)        
            return QVariant(QColor(bgColor))


class Proxy01(QSortFilterProxyModel):
    def __init__(self):
        super(Proxy01, self).__init__()

    def filterAcceptsRow(self, row, parent):
        if row%3: return True
        else: return False

class MyWindow(QWidget):
    def __init__(self, *args):
        QWidget.__init__(self, *args)

        self.tablemodel=MyTableModel(self)               

        self.proxy1=Proxy01()
        self.proxy1.setSourceModel(self.tablemodel)

        tableviewA=QTableView(self) 
        tableviewA.setModel(self.proxy1)
        tableviewA.setSortingEnabled(True) 
        tableviewA.horizontalHeader().setSortIndicator(0, Qt.AscendingOrder)
        tableviewA.horizontalHeader().setStretchLastSection(True)

        layout = QVBoxLayout(self)
        layout.addWidget(tableviewA)

        self.setLayout(layout)

    def test(self, arg):
        print arg

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_()) 

推荐答案

而不是依赖源模型的 data()if Qt.BackgroundColorRole: 方法的功能集tableviewA.setAlternatingRowColors(True)True.它与 CSS 配合得很好.下面发布了一个完整的解决方案(请注意,Qt.BackgroundColorRole 已被注释掉.否则它会优先于 CSS):

Instead of relying on source model's data()'s if Qt.BackgroundColorRole: method's functionality set tableviewA.setAlternatingRowColors(True) to True. It works beautifully with CSS. A fully working solution is posted below (please note that Qt.BackgroundColorRole has been commented out. Otherwise it would take precedence over the CSS):

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

class MyTableModel(QAbstractTableModel):
    def __init__(self, parent=None, *args):
        QAbstractTableModel.__init__(self, parent, *args)
        self.items = [i for i in range(90)]

    def rowCount(self, parent):
        return len(self.items)       
    def columnCount(self, parent):
        return 1

    def data(self, index, role):
        if not index.isValid():
            return QVariant()

        row=index.row()
        column=index.column()

        if role == Qt.DisplayRole:
            if row<len(self.items):
                return QVariant(self.items[row])
            else:
                return QVariant()

        # if role==Qt.BackgroundColorRole:
        #     if row%2: bgColor=QColor(Qt.green)
        #     else: bgColor=QColor(Qt.blue)        
        #     return QVariant(QColor(bgColor))


class Proxy01(QSortFilterProxyModel):
    def __init__(self):
        super(Proxy01, self).__init__()

    def filterAcceptsRow(self, row, parent):
        if row%3: return True
        else: return False

class MyWindow(QWidget):
    def __init__(self, *args):
        QWidget.__init__(self, *args)

        self.tablemodel=MyTableModel(self)               

        self.proxy1=Proxy01()
        self.proxy1.setSourceModel(self.tablemodel)

        tableviewA=QTableView(self) 
        tableviewA.setModel(self.proxy1)
        tableviewA.setSortingEnabled(True) 
        tableviewA.horizontalHeader().setSortIndicator(0, Qt.AscendingOrder)
        tableviewA.horizontalHeader().setStretchLastSection(True)
        tableviewA.setAlternatingRowColors(True)
        tableviewA.setStyleSheet("alternate-background-color: yellow; background-color: red;");

        layout = QVBoxLayout(self)
        layout.addWidget(tableviewA)

        self.setLayout(layout)

    def test(self, arg):
        print arg

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_()) 

这篇关于如何控制QTableView Items的背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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