void MyWindow::initializeModelBySQL(QSqlQueryModel *model,QTableView *table,QString sql){
model = new QSqlQueryModel(this);
model->setQuery(sql);
}
With this method i can set a QSQlQueryModels to my QTableviews.
But How i can set color to a row based on a cell value?
The view draws the background based on the
Qt::BackgroundRole
role of the cell which is theQBrush
value returned byQAbstractItemModel::data(index, role)
for that role.You can subclass the
QSqlQueryModel
to redefinedata()
to return your calculated color, or if you have Qt > 4.8, you can use aQIdentityProxyModel
:And use that model in the view, with the sql model set as source with
QIdentityProxyModel::setSourceModel
.OR
You can keep the model unchanged and modify the background with a delegate set on the view with
QAbstractItemView::setItemDelegate
:As the last method is not always obvious to translate from C++ code, here is the equivalent in python:
Your best bet is to define a custom model (
QAbstractTableModel
subclass). You probably want to have aQSqlQueryModel
as a member in this custom class.If it's a read-only model, you need to implement at least these methods:
and for well behaved models also
If you need the model to be able to edit/submit data, things get a bit more involved and you will also need to implement these methods:
What will actually change a row appearance lies in the return value of this method:
A dumb example: