I’m looking for a way to add color text in rows being displayed in a pyside6 app. For example in the code below, if the “City” is “New York” I want all of the text in that row to be red.
import sys
import pandas as pd
from PySide6.QtWidgets import QApplication, QMainWindow, QTableView, QVBoxLayout, QWidget
from PySide6.QtCore import QAbstractTableModel, Qt
class DataFrameModel(QAbstractTableModel):
def __init__(self, df=pd.DataFrame(), parent=None):
super(DataFrameModel, self).__init__(parent)
self._df = df
def rowCount(self, parent=None):
return self._df.shape[0]
def columnCount(self, parent=None):
return self._df.shape[1]
def data(self, index, role=Qt.DisplayRole):
if index.isValid():
if role == Qt.DisplayRole:
return str(self._df.iloc[index.row(), index.column()])
return None
def headerData(self, section, orientation, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
return self._df.columns[section]
elif orientation == Qt.Vertical:
return str(self._df.index[section])
return None
class MainWindow(QMainWindow):
def __init__(self, df, parent=None):
super(MainWindow, self).__init__(parent)
self.setWindowTitle("Pandas DataFrame Viewer")
self.model = DataFrameModel(df)
self.view = QTableView()
self.view.setModel(self.model)
layout = QVBoxLayout()
layout.addWidget(self.view)
container = QWidget()
container.setLayout(layout)
self.setCentralWidget(container)
if __name__ == "__main__":
app = QApplication(sys.argv)
# Example data: list of lists
data = [
["John Doe", 29, "New York"],
["Jane Doe", 32, "Los Angeles"],
["Mike Roe", 45, "Chicago"]
]
# Specify column names
column_names = ["Name", "Age", "City"]
# Create DataFrame
df = pd.DataFrame(data, columns=column_names)
# Display DataFrame in a PySide6 application
window = MainWindow(df)
window.show()
sys.exit(app.exec())