【发布时间】:2020-05-01 00:23:07
【问题描述】:
我从QTableView refresh 获得了大部分代码。
我从 SQL 数据库中提取数据并通过 Pandas DataFrame 将其呈现给 QAbstractTableModel 并使用 QTableView 显示。一切正常(感谢上述文章的重大帮助)。现在的问题是我只想为第二列中的文本着色,这与我在数据函数的颜色决策中使用的列相同。
我已经调试了代码,发现“it”变量中的值只是我想要着色的值,所以在我看来,当“return qtg.QBrush(qtc.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)
【问题讨论】:
-
我发布了我的整个代码,检查上面的编辑。