【问题标题】:pyqt - Change row~cell color in TableViewpyqt - 在 TableView 中更改行~单元格颜色
【发布时间】:2013-03-15 08:41:18
【问题描述】:

我有一个包含三列的 QTableView 第二列是关于数字的,只有三种类型:1、-1和0。 我想为这三种“类型”的数字(1、-1、0)设置不同的颜色,用不同的颜色为它们的行着色。我该怎么做?

 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)

obs:我使用了horizontalheader().setStrechLastSection(True),因为我在 tableview 中打开了一个现有的 csv 文件(使用按钮)。

【问题讨论】:

    标签: python qt pyqt4 tableview background-color


    【解决方案1】:

    您必须在模型中定义颜色,而不是在视图中:

    def data(self, index, role):
        ...
        if role == Qt.BackgroundRole:
            return QBrush(Qt.yellow)
    

    编辑: 这是一个工作示例,除了完全从http://www.saltycrane.com/blog/2007/06/pyqt-42-qabstracttablemodelqtableview/盗取的颜色部分

    from PyQt4.QtCore import *
    from PyQt4.QtCore import *
    from PyQt4.QtGui import *
    import sys
    
    my_array = [['00','01','02'],
                ['10','11','12'],
                ['20','21','22']]
    
    def main():
        app = QApplication(sys.argv)
        w = MyWindow()
        w.show()
        sys.exit(app.exec_())
    
    class MyWindow(QTableView):
        def __init__(self, *args):
            QTableView.__init__(self, *args)
    
            tablemodel = MyTableModel(my_array, self)
            self.setModel(tablemodel)
    
    class MyTableModel(QAbstractTableModel):
        def __init__(self, datain, parent=None, *args):
            QAbstractTableModel.__init__(self, parent, *args)
            self.arraydata = datain
    
        def rowCount(self, parent):
            return len(self.arraydata)
    
        def columnCount(self, parent):
            return len(self.arraydata[0])
    
        def data(self, index, role):
            if not index.isValid():
                return QVariant()
            # vvvv this is the magic part
            elif role == Qt.BackgroundRole:
                if index.row() % 2 == 0:
                    return QBrush(Qt.yellow)
                else:
                    return QBrush(Qt.red)
            # ^^^^ this is the magic part
            elif role != Qt.DisplayRole:
                return QVariant()
            return QVariant(self.arraydata[index.row()][index.column()])
    
    if __name__ == "__main__":
        main()
    

    【讨论】:

    • ..首先,谢谢。但是,你能给我举个例子吗?就像用两条不同颜色的线创建一个tableview?我正在尝试,但我从未做过这样的事情。
    • 我还有一个关于颜色的问题,但现在使用一个按钮为现有数据的表格着色。 stackoverflow.com/questions/15666635/…
    猜你喜欢
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 2014-07-15
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多