How to set row color in tableview with qsqltablemodel ?
-
Pyside2 has not qvariant, this code only return the color and not data. Thanks!
class TableModel: def __init__(self): super().__init__() self.DB = QSqlDatabase.addDatabase("QSQLITE") self.DB.setDatabaseName(r"test.db") self.query = QSqlQuery(self.DB) self.tabModel = QSqlTableModel() self.tabModel.setTable("TotalTable") self.tabModel.data = self.data self.tabModel.select() self.selModel = QItemSelectionModel(self.tabModel) def data(self, index, role=Qt.DisplayRole): if role == Qt.BackgroundRole: if index.row() % 2 == 0: return QBrush(Qt.yellow) else: return QBrush(Qt.red)
-
I have solved this issue. But I think It is not perfect. I hope that user can right click the tableview and set the row color.
class CustomSqlModel(QSqlTableModel): def data(self, index, role=Qt.DisplayRole): if role == Qt.BackgroundRole: if index.row() in [1]: return QBrush(Qt.red) elif index.row() in [2]: return QBrush(Qt.green) elif index.row() in [3]: return QBrush(Qt.blue) elif index.row() in [4]: return QBrush(Qt.yellow) return QSqlTableModel.data(self, index, role)
-
mmm it's not clear to me what you want to achieve. Do you mind explaining a bit more what is the final goal? it seems I'm missing something from the "right click and change color"
-
@Cedric-Niu said in How to set row color in tableview with qsqltablemodel ?:
I hope that user can right click the tableview and set the row color.
As @CristianMaureira has said, it is not clear what you mean here, and it is unrelated to what went before. If you do want to do this, you are going to have to store somewhere what row(s) the user has clicked on and what color(s) they selected for the row(s).
-