아래에 표시된 QAbstractTableModel을 기반으로 'pandasModel'클래스를 만듭니다.
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class pandasModel(QAbstractItemModel):
def __init__(self, data, parent=None):
QAbstractItemModel.__init__(self, parent)
self._data = data
def rowCount(self, parent=None):
return self._data.index.size
def columnCount(self, parent=None):
return self._data.columns.size
def data(self, index, role=Qt.DisplayRole):
if index.isValid():
if role == Qt.DisplayRole:
return str(self._data.iloc[index.row(), index.column()])
if role == Qt.EditRole:
return str(self._data.iloc[index.row(), index.column()])
return None
def headerData(self, rowcol, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self._data.columns[rowcol]
if orientation == Qt.Vertical and role == Qt.DisplayRole:
return self._data.index[rowcol]
return None
def flags(self, index):
flags = super(self.__class__, self).flags(index)
flags |= Qt.ItemIsEditable
flags |= Qt.ItemIsSelectable
flags |= Qt.ItemIsEnabled
flags |= Qt.ItemIsDragEnabled
flags |= Qt.ItemIsDropEnabled
return flags
def sort(self, Ncol, order):
"""Sort table by given column number.
"""
try:
self.layoutAboutToBeChanged.emit()
self._data = self._data.sort_values(self._data.columns[Ncol], ascending=not order)
self.layoutChanged.emit()
except Exception as e:
print(e)
또한 아래에 표시된 모델을 표시하기 위해 QTableView를 만듭니다.
class TableWin(QWidget):
pos_updown = -1
pos_save = []
def __init__(self):
super(TableWin, self).__init__()
self.resize(200, 100)
self.table = QTableView(self)
self.v_layout = QVBoxLayout()
self.v_layout.addWidget(self.table)
self.setLayout(self.v_layout)
self.showdata()
def showdata(self):
data = pd.DataFrame([[1,2,3,4],[5,6,7,8]])
model = pandasModel(data)
self.table.setModel(model)
def set_cell_color(self, row, column)
'''
Pass two arguments to this function, which is called to set
the background color of the cell corresponding to the row and column
'''
if __name__ == '__main__':
app = QApplication(sys.argv)
tableView = TableWin()
# I want to change cell's color by call function 'set_cell_color' here
# tableView.set_cell_color(row=1,column=1)
tableView.show()
sys.exit(app.exec_())
이제 QTableview에서 데이터를 표시 할 수 있지만 질문은 'set_cell_color'함수를 호출하여 주어진 행과 열이있는 셀의 배경색을 설정하는 방법입니다. def set_cell_color에서 코드를 완료하는 방법을 알려주세요.
일단 QStandardItemModel과 마찬가지로 'model.item (row, col) .setBackground (QColor (240, 255, 240))'을 사용하여 셀의 색상을 설정하고 싶지만 오류 ''model '에는'item '속성이 없습니다.
코드는 다음과 같습니다.
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class Model(QAbstractTableModel):
def __init__(self, parent=None):
super(Model, self).__init__(parent)
self._data = [[['%d - %d' % (i, j), False] for j in range(10)] for i in range(10)]
def rowCount(self, parent):
return len(self._data)
def columnCount(self, parent):
return len(self._data[0])
def flags(self, index):
return Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable
def data(self, index, role):
if index.isValid():
data, changed = self._data[index.row()][index.column()]
if role in [Qt.DisplayRole, Qt.EditRole]:
return data
if role == Qt.BackgroundRole and data == "In error": # <---------
return QBrush(Qt.red)
def setData(self, index, value, role):
if role == Qt.EditRole:
self._data[index.row()][index.column()] = [value, True]
self.dataChanged.emit(index, index)
return True
return False
if __name__ == '__main__':
app = QApplication(sys.argv)
tableView = QTableView()
m = Model(tableView)
tableView.setModel(m)
tableView.show()
sys.exit(app.exec_())
'데이터'함수에서 'return QBrush (Qt.red)'를 사용하면 '오류 있음'값으로 셀의 배경색을 설정할 수 있지만 Qtableview가 생성 될 때 배경색이 이미 설정되어 있으므로 설정하고 싶습니다. 'set_cell_color'함수를 호출 할 때 셀의 배경색, 즉 Qtableview가 이미 생성 된 후에도 셀의 배경을 제어 할 수 있다는 의미입니다. 도움을 주셔서 감사합니다.
논리는 항목의 위치와 항목의 색상을 연결하는 정보를 모델에 저장하고이를 업데이트하려면 dataChanged 신호를 내 보내야합니다.
참고 : 모델은 테이블 유형이므로 QAbstractItemModel이 아닌 QAbstractTableModel에서 상속해야합니다.
위의 내용을 고려할 때 해결책은 다음과 같습니다.
class pandasModel(QAbstractTableModel):
def __init__(self, data, parent=None):
QAbstractItemModel.__init__(self, parent)
self._data = data
self.colors = dict()
def rowCount(self, parent=None):
return self._data.index.size
def columnCount(self, parent=None):
return self._data.columns.size
def data(self, index, role=Qt.DisplayRole):
if index.isValid():
if role == Qt.DisplayRole:
return str(self._data.iloc[index.row(), index.column()])
if role == Qt.EditRole:
return str(self._data.iloc[index.row(), index.column()])
if role == Qt.BackgroundRole:
color = self.colors.get((index.row(), index.column()))
if color is not None:
return color
return None
def headerData(self, rowcol, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self._data.columns[rowcol]
if orientation == Qt.Vertical and role == Qt.DisplayRole:
return self._data.index[rowcol]
return None
def flags(self, index):
flags = super(self.__class__, self).flags(index)
flags |= Qt.ItemIsEditable
flags |= Qt.ItemIsSelectable
flags |= Qt.ItemIsEnabled
flags |= Qt.ItemIsDragEnabled
flags |= Qt.ItemIsDropEnabled
return flags
def sort(self, Ncol, order):
"""Sort table by given column number.
"""
try:
self.layoutAboutToBeChanged.emit()
self._data = self._data.sort_values(
self._data.columns[Ncol], ascending=not order
)
self.layoutChanged.emit()
except Exception as e:
print(e)
def change_color(self, row, column, color):
ix = self.index(row, column)
self.colors[(row, column)] = color
self.dataChanged.emit(ix, ix, (Qt.BackgroundRole,))
class TableWin(QWidget):
pos_updown = -1
pos_save = []
def __init__(self):
super(TableWin, self).__init__()
self.resize(200, 100)
self.table = QTableView(self)
self.v_layout = QVBoxLayout()
self.v_layout.addWidget(self.table)
self.setLayout(self.v_layout)
self.showdata()
def showdata(self):
data = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]])
self.model = pandasModel(data)
self.table.setModel(self.model)
def set_cell_color(self, row, column):
self.model.change_color(row, column, QBrush(Qt.red))
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다