【发布时间】:2022-02-07 20:59:36
【问题描述】:
我有一个带有 QAbstractTableModel 的 QTableView。单击一个单元格时,我想更改行背景颜色。我知道至少有两种方法可以在单击一个单元格时更改行背景颜色。一种是使用委托,另一种是使用 QAbstractTable 中的 setData 方法。但我一个都没有,,,哎呀。在这里,我尝试在 QAbstractTable 中使用 setData 方法来更改所选单元格的背景颜色,但失败了!您能否帮助我更正我的代码以更改整行颜色而不仅仅是一个单元格。无论如何,更改单元格颜色甚至都不行!非常感谢!代码如下
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_()
【问题讨论】:
标签: pyqt5 selection qtableview