我对PyQT非常陌生,偶然发现了以下障碍。我创建了一个pandas DataFrame并设法在pyqt4表视图中使用在另一个线程(Fastest way to populate QTableView from Pandas data frame)中找到的一些代码对其进行了可视化处理。现在,我要突出显示每一行中的最高值。
目前,我用于将pandas DataFrame加载到“表格视图”中的代码如下:
class PandasModel(QtCore.QAbstractTableModel):
"""
Class to populate a table view with a pandas dataframe
"""
def __init__(self, data, parent=None):
QtCore.QAbstractTableModel.__init__(self, parent)
self._data = data
def rowCount(self, parent=None):
return len(self._data.values)
def columnCount(self, parent=None):
return self._data.columns.size
def data(self, index, role):
if index.isValid():
if role == QtCore.Qt.DisplayRole:
return str(self._data.values[index.row()][index.column()])
return None
def headerData(self, col, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self._data.columns[col]
return None
我不知道使用这种方法是否可以实现我想实现的目标,因为我认为我对PyQT的结构不够了解,因此欢迎任何解决方案。
我想要的结果最终看起来像是this
提前谢谢!
答案 0 :(得分:0)
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QTreeWidgetItem
import sys
import pandas as pd
import numpy as np
class PandasModel(QtCore.QAbstractTableModel):
"""
Class to populate a table view with a pandas dataframe
"""
def __init__(self, data, parent=None):
QtCore.QAbstractTableModel.__init__(self, parent)
self._data = data
def rowCount(self, parent=None):
return len(self._data.values)
def columnCount(self, parent=None):
return self._data.columns.size
def data(self, index, role):
if index.isValid():
if role == QtCore.Qt.DisplayRole:
return str(self._data.values[index.row()][index.column()])
if role == QtCore.Qt.BackgroundColorRole:
row = index.row()
col = index.column()
if self._data.iloc[row,col] == self._data.iloc[row].max():
color = QtGui.QColor('red')
else:
color = QtGui.QColor('white')
pixmap = QtGui.QPixmap(26, 26)
pixmap.fill(color)
return color
return None
def headerData(self, col, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self._data.columns[col]
return None
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
df = pd.DataFrame(np.random.randn(8,3).round(3))
view = QtWidgets.QTableView()
view.setModel(PandasModel(df))
view.show()
sys.exit(app.exec_())