カスタムQTableView
とカスタムがありますQAbstractTableModel
。ビューでは、単一の選択のみが許可されます。いくつかの条件下で、選択したセルの背景色をカスタマイズしようとしていますが、うまくいきません。data
モデルのselectionChanged
方法とビューの方法を組み合わせることでそれができると期待していました。たとえば、選択したセルが特定の行に一致するときに、そのセルの色を変更したいとします。selectionChanged
メソッドの私のコードは次のとおりです。
def selectionChanged(self, selected, deselected):
#QtGui.QTableView.selectionChanged(self, selected, deselected)
# Get the selected indexes from the QItemSelection object
selection = selected.indexes()
# Let the model track the selected cell
self.tmodel.selected_index = selection[0]
# Desperately try to make it work
self.tmodel.dataChanged.emit(selection[0], selection[0])
self.viewport().update()
data
メソッドの単純化されたコードは次のとおりです。
def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid():
return None
# Some code here dealing with several roles
if role == QtCore.Qt.DisplayRole:
...
elif role == QtCore.Qt.BackgroundRole:
if ((index == self.selected_index) and (index.row() == 3)):
print '++++ displaying selected'
return QtGui.QColor(QtCore.Qt.yellow)
else:
return QtGui.QColor(QtCore.Qt.green)
else:
return None
選択されていないセルの背景は、予想どおり緑色です。奇妙なことに、一致する行のセルを選択すると、メッセージ++++ displaying selected
が印刷されますが、選択したセルの背景が黄色ではなくシステムのデフォルトの背景になります。ここで重要/明白な何かが欠けているに違いありませんが、それが何であるかはわかりません。
アップデート
カスタム デリゲートを使用してそのメソッドを実装することで目標を達成できることはわかってpaint
いますが、上記のコードが失敗する理由を知りたいです。