我对 PyQT 很陌生,偶然发现了以下障碍。我创建了一个 Pandas DataFrame 并设法在 pyqt4 Table View 中使用我在另一个线程中找到的一些代码将它可视化(从 Pandas 数据框填充 QTableView 的最快方法)。现在我想突出显示每一行中的最高值。
目前,我用于将 Pandas DataFrame 加载到 Table View 的代码如下所示:
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 结构,因此欢迎任何解决方案。
理想的结果我想到最后会像这样的例子
先感谢您!
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_())
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句