TableView background color
Unsolved
C++ Gurus
-
Hello,
I am new in qt and c++ and hope that someone can help me.
I will change the background color in a TableView for some cells, but it doesn't work.tableanpassen.cpp
Tableanpassen::Tableanpassen(QObject *parent):QSqlRelationalTableModel (parent) { } QVariant Tableanpassen::data(const QModelIndex &index, int role) const { int row = index.row(); int col = index.column(); if(role == Qt::BackgroundRole) { if (row == 1 && col == 2) //change background only for cell(1,2) { QBrush Background(Qt::red); return Background; } } return QSqlRelationalTableModel::data(index, role); }
tableanpassen.h
#ifndef TABLEANPASSEN_H #define TABLEANPASSEN_H //#include <QSqlQueryModel> #include "QSqlRelationalTableModel" class Tableanpassen : public QSqlRelationalTableModel { Q_OBJECT public: Tableanpassen(QObject *parent = nullptr); QVariant data(const QModelIndex &item, int role) const; }; #endif // TABLEANPASSEN_H
and in the .cpp below i set the model but I think there is the mistake.
test_screen::test_screen(QWidget *parent) : QMainWindow(parent), ui(new Ui::test_screen) { ui->setupUi(this); model = new QSqlRelationalTableModel(this); model->setQuery("SELECT * FROM WekzeugWechselWarnung"); model->setHeaderData(0, Qt::Horizontal, tr("Werkzeug Nr.")); model->setHeaderData(1, Qt::Horizontal, tr("Zeit")); model->setData(model->index(1,2),QBrush(Qt::red), Qt::BackgroundRole); (is that right) ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); ui->tableView->setModel(model); ...
Thank you for help.
[koahnig:code tags added]
-
@Mogli123
just to make sure: indexes are 0-based. So first row/column has an index of 0 not 1.
In case you only showing 1 row of data in your table and wondering why the background doesn't get applied.