Формат ForegroundRole для отдельной ячейки - PullRequest
0 голосов
/ 01 апреля 2020

Я получил большую часть этого кода из QTableView refre sh.

У меня есть данные, извлеченные из базы данных SQL, и я передаю их в QAbstractTableModel через Pandas DataFrame и отобразить его с помощью QTableView. Все работает (благодаря значительной помощи из вышеупомянутой статьи). Теперь проблема в том, что я хотел бы просто раскрасить текст во 2-м столбце, который является тем же столбцом, который я использую при выборе цвета в функции данных.

Я отладил код, чтобы увидеть, что значение в переменной "it" является только значением, которое я хочу раскрасить, поэтому мне кажется, что когда "return qtg.QBru sh (qt c .QT. "COLOR") применяется для того, чтобы он только окрашивал эти данные, а вместо этого окрашивал всю строку.

Любая помощь в понимании того, как работает этот фрагмент кода, будет принята с благодарностью!

import sys
import threading

import pandas as pd

from PyQt5 import QtCore as qtc
from PyQt5 import QtGui as qtg
from PyQt5 import QtWidgets as qtw

import data
import pyodbc


class PandasManager(qtc.QObject):
    dataFrameChanged = qtc.pyqtSignal(pd.DataFrame)

    def start(self):
        self.t = threading.Timer(0, self.load)
        self.t.start()

    def load(self):
        df = data.get_data()

        self.dataFrameChanged.emit(df)
        self.t = threading.Timer(5.0, self.load)
        self.t.start()

    def stop(self):
        self.t.cancel()


class PandasModel(qtc.QAbstractTableModel):
    def __init__(self, df=pd.DataFrame()):
        qtc.QAbstractTableModel.__init__(self)
        self._df = df

    @qtc.pyqtSlot(pd.DataFrame)
    def setDataFrame(self, df):
        self.beginResetModel()
        self._df = df
        self.endResetModel()

    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=qtc.Qt.DisplayRole):
        if index.isValid():  #Checking the validity of the index
            if role == qtc.Qt.ForegroundRole: # The role for text color
                if self.columnCount() >= 3 : # checking the number of columns is greater than 3 (Should be 5)
                    it = self._df.iloc[index.row(), 1] # Finds the specific data (second column) to test and assigns it to the variable "it"
                    if it == "WE": # If the value matches
                        return qtg.QBrush(qtc.Qt.yellow) #Color -- I may not quite understand what this is actually doing
                    if it == "UMaint": # Another value to match
                        return qtg.QBrush(qtc.Qt.green) # Another color
            if role == qtc.Qt.DisplayRole: # If not ForegroundRole but is DisplayRole
                return str(self._df.iloc[index.row(), index.column()]) #Set value

    def headerData(self, col, orientation, role):
        if orientation == qtc.Qt.Horizontal and role == qtc.Qt.DisplayRole:
            return self._df.columns[col]
        return None


if __name__ == "__main__":
    app = qtw.QApplication(sys.argv)
    w = qtw.QTableView()
    model = PandasModel()
    w.setModel(model)
    w.show()

    manager = PandasManager()
    manager.dataFrameChanged.connect(model.setDataFrame)
    manager.start()

    ret = app.exec_()

    manager.stop()

    sys.exit(ret)

1 Ответ

0 голосов
/ 03 апреля 2020

Мне удалось заставить код работать так, как я хотел, и я вставляю его ниже. Я уверен, что есть гораздо более чистый и более «pythoni c» способ сделать это, но он работает.

Что касается разницы, которая заставила его работать, я не совсем уверен. Я реализовал переменную для индекса столбца, чтобы помочь мне понять, что происходит, и я удалил счетчик столбцов if, но кроме этого я не уверен.

Ниже приведен мой рабочий код, который, возможно, поможет другие в будущем.

def data(self, index, role=QtCore.Qt.DisplayRole):

        current_column = index.column()
        current_row = index.row()

        we_color = QtGui.QColor('#FF9900')
        wp_color = QtGui.QColor('#CCCC33')
        umaint_color = QtGui.QColor('#FF0000')
        smaint_color = QtGui.QColor('#FA8072')
        equipinstall_color = QtGui.QColor('#0066FF')
        upartwt_color = QtGui.QColor('#990099')
        le_color = QtGui.QColor('#CC6600')
        prodrun_color = QtGui.QColor('#00FF00')
        matlassist_color = QtGui.QColor('#CC9999')
        oqual_color = QtGui.QColor('#C993FF')
        equipeng_color = QtGui.QColor('#B22222')

        white_color = QtGui.QColor(QtCore.Qt.white)
        black_color = QtGui.QColor(QtCore.Qt.black)

        if index.isValid():  # Checking the validity of the index
            if role == QtCore.Qt.ForegroundRole:  # The role for text color
                if current_column == 1:  # checking the number of columns is greater than 3 (Should be 5)
                    it = self._dataframe.iloc[index.row(), current_column]  # Finds the specific data (second column) to test and assigns it to the variable "it"
                    if it == "WE":  # If the value matches
                        return QtGui.QBrush(black_color)  # Color -- I may not quite understand what this is actually doing
                    if it == "WP":  # Another value to match
                        return QtGui.QBrush(black_color)  # Another color+
                    if it == "SMaint":  # Another value to match
                        return QtGui.QBrush(black_color)  # Another color+
                    if it == "UMaint":  # Another value to match
                        return QtGui.QBrush(white_color)  # Another color+
                    if it == "EquipInstall":  # Another value to match
                        return QtGui.QBrush(black_color)  # Another color+
                    if it == "UPartWt":  # Another value to match
                        return QtGui.QBrush(white_color)  # Another color+
                    if it == "LE":  # Another value to match
                        return QtGui.QBrush(black_color)  # Another color+
                    if it == "ProdRun":  # Another value to match
                        return QtGui.QBrush(black_color)  # Another color+
                    if it == "MatlAssist":  # Another value to match
                        return QtGui.QBrush(black_color)  # Another color+
                    if it == "OQual":  # Another value to match
                        return QtGui.QBrush(black_color)  # Another color+
                    if it == "EquipEng":  # Another value to match
                        return QtGui.QBrush(black_color)  # Another color+

            if role == QtCore.Qt.BackgroundColorRole:  # The role for text color
                if current_column == 1:
                    it = self._dataframe.iloc[index.row(), current_column]  # Finds the specific data (second column) to test and assigns it to the variable "it"
                    if it == "WE":  # If the value matches
                        return QtGui.QBrush(we_color)  # Color -- I may not quite understand what this is actually doing
                    if it == "WP":  # Another value to match
                        return QtGui.QBrush(wp_color)  # Another color+
                    if it == "SMaint":  # Another value to match
                        return QtGui.QBrush(smaint_color)  # Another color+
                    if it == "UMaint":  # Another value to match
                        return QtGui.QBrush(umaint_color)  # Another color+
                    if it == "EquipInstall":  # Another value to match
                        return QtGui.QBrush(equipinstall_color)  # Another color+
                    if it == "UPartWt":  # Another value to match
                        return QtGui.QBrush(upartwt_color)  # Another color+
                    if it == "LE":  # Another value to match
                        return QtGui.QBrush(le_color)  # Another color+
                    if it == "ProdRun":  # Another value to match
                        return QtGui.QBrush(prodrun_color)  # Another color+
                    if it == "MatlAssist":  # Another value to match
                        return QtGui.QBrush(matlassist_color)  # Another color+
                    if it == "OQual":  # Another value to match
                        return QtGui.QBrush(oqual_color)  # Another color+
                    if it == "EquipEng":  # Another value to match
                        return QtGui.QBrush(equipeng_color)  # Another color+

            if role == QtCore.Qt.DisplayRole:  # If not ForegroundRole but is DisplayRole
                return str(self._dataframe.iloc[index.row(), index.column()])  # Set value
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...