首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python PyQt5 QTableView更改选定的行背景颜色

Python PyQt5 QTableView更改选定的行背景颜色
EN

Stack Overflow用户
提问于 2022-02-06 08:28:13
回答 1查看 430关注 0票数 0

我有QTableView和QAbstractTableModel。单击一个单元格时,要更改行背景颜色。我知道至少有两种方法可以在单击一个单元格时更改行背景颜色。一种是使用委托,另一种是在setData中使用QAbstractTable方法。但我没有,,,噢。在这里,我尝试使用setData方法在QAbstractTable中只更改选定的单元格背景颜色,但失败了!请您帮我更正一下代码,以便更改整行颜色,而不仅仅是一个单元格。总之,改变细胞颜色是不可能的!非常感谢!代码如下

代码语言:javascript
复制
import sys
import typing
import numpy as np
import pandas as pd
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow, \
    QWidget, QTableView, QVBoxLayout
from PyQt5.QtCore import QAbstractTableModel, Qt, QModelIndex

class MyTableModel(QAbstractTableModel):
    def __init__(self, data:pd.DataFrame):
        super().__init__()
        self._data = data

    def data(self, index: QModelIndex, role: int = ...) -> typing.Any:
        if role==Qt.DisplayRole:
            value = str(self._data.iloc[index.row()][index.column()])
            return value

    def setData(self, index: QModelIndex, value: typing.Any, role: int = ...) -> bool:
        if not index.isValid():
            return False
        else:
            if role==Qt.BackgroundColorRole:
                self.dataChanged.emit(index, index, [role])
                return True


    def rowCount(self, parent: QModelIndex = ...) -> int:
        return self._data.shape[0]

    def columnCount(self, parent: QModelIndex = ...) -> int:
        return self._data.shape[1]


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.myTable = QTableView()
        df = self.get_DataFrame_Data()
        self.model = MyTableModel(df)
        self.myTable.setModel(self.model)
        self.myTable.clicked.connect(self.change_row_bgcolor)
        hlayout = QVBoxLayout()
        hlayout.addWidget(self.myTable)
        dummy_widget = QWidget()
        dummy_widget.setLayout(hlayout)
        self.setCentralWidget(dummy_widget)
        self.setFixedSize(600, 600)

    def get_DataFrame_Data(self):
        ndarray = np.random.randint(10, 50, (7, 3))
        df = pd.DataFrame(data=ndarray, columns=['col1','col2','col3'])
        return df

    def change_row_bgcolor(self, index):
        self.model.setData(index,Qt.red,Qt.BackgroundColorRole)


app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-07 12:50:16

解决了!用户鼠标点击时改变QTableView行背景色的两种方法。

  1. 使用QStyledItemDelegate。子类QStyledItemDelegate.您应该设置一个类属性(etc tableview的currentindex),它可以从类外部重置值,这样,委托的默认循环将比较tableview的currentindex.Code:

代码语言:javascript
复制
    class TableDelegate(QStyledItemDelegate):
        
        select_index = None
    
        def paint(self, painter: QtGui.QPainter, option: 'QStyleOptionViewItem', index: QtCore.QModelIndex) -> None:
            # option.state
            row = index.row()
            column = index.column()
            select_row = self.select_index.row()
            # self.initStyleOption(option,index)
            if row == select_row:
                # option.font.setItalic(True)
                option.font.setStyle(QFont.StyleOblique)
                bg = QColor(135, 206, 255)
                painter.fillRect(option.rect, bg)
                # painter.eraseRect(option.rect)
            QStyledItemDelegate.paint(self, painter, option, index)

  1. 使用QAbstractTableModel.Also,您应该设置一个类属性,而不是将方法data()的默认循环与类属性(tableview的当前索引)进行比较。

代码语言:javascript
复制
    class MyTableModel(QAbstractTableModel):
        def __init__(self, data:pd.DataFrame):
            super().__init__()
            self._data = data
            self.color_enabled = False
            self.color_back = Qt.magenta
            self.target_row = -1
    
        def data(self, index: QModelIndex, role: int) -> typing.Any:
            if role==Qt.DisplayRole:
                # print(index.row())
                value = str(self._data.iloc[index.row()][index.column()])
                return value
            if role == Qt.BackgroundRole and index.row()==self.target_row \
                    and self.color_enabled==True:
                return QBrush(self.color_back)

还有,,!这里还有另一个特别的问题需要强调。当用户单击一个单元格时,在我的计算机中看到的默认背景是蓝色的。如果希望在单击时整行背景色相同,则应在创建QTableView后执行此操作:

代码语言:javascript
复制
self.myTable.setStyleSheet("QTableView::item:selected{"
                   "background:rgb(135, 206, 255)}")

这意味着,通过QSS设置选定的单元格bgcolor,然后,在使用QAbstractTableModel的data()方法或QStyledItemDelege中的pain()方法时,应该设置相同的颜色。那一切都好了!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71005418

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档