我有QTableView和QAbstractTableModel。单击一个单元格时,要更改行背景颜色。我知道至少有两种方法可以在单击一个单元格时更改行背景颜色。一种是使用委托,另一种是在setData中使用QAbstractTable方法。但我没有,,,噢。在这里,我尝试使用setData方法在QAbstractTable中只更改选定的单元格背景颜色,但失败了!请您帮我更正一下代码,以便更改整行颜色,而不仅仅是一个单元格。总之,改变细胞颜色是不可能的!非常感谢!代码如下
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_()发布于 2022-02-07 12:50:16
解决了!用户鼠标点击时改变QTableView行背景色的两种方法。
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) 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后执行此操作:
self.myTable.setStyleSheet("QTableView::item:selected{"
"background:rgb(135, 206, 255)}")这意味着,通过QSS设置选定的单元格bgcolor,然后,在使用QAbstractTableModel的data()方法或QStyledItemDelege中的pain()方法时,应该设置相同的颜色。那一切都好了!

https://stackoverflow.com/questions/71005418
复制相似问题