relation beetwen Qtableview and modele
-
Good morning,
How color lines of my view with a model. I don't know to do.
Thank you, this is my code.
fenetre.h
#ifndef FENETRE_H
#define FENETRE_H#include <QWidget>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlQueryModel>
#include <QSqlTableModel>
#include "monmodele.h"namespace Ui {
class Fenetre;
}class monModele;
class Fenetre : public QWidget
{
Q_OBJECTpublic:
explicit Fenetre(QWidget *parent = 0);
~Fenetre();void ouvrirBase(); private: Ui::Fenetre *ui; QSqlQuery *mRequete; QSqlQueryModel *sqlModele; QSqlDatabase mDatabase; };
#endif // FENETRE_H
fenetre.cpp
#include "fenetre.h"
#include "monmodele.h"
#include "ui_fenetre.h"Fenetre::Fenetre(QWidget *parent) :
QWidget(parent),
ui(new Ui::Fenetre)
{
ui->setupUi(this);
}Fenetre::~Fenetre()
{
delete ui;
}void Fenetre::ouvrirBase()
{
QString file = "C:\test\bd1.accdb";
mDatabase = QSqlDatabase::addDatabase("QODBC");
QString dataBaseString = "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};FIL={MS Access};DBQ=" + file;
mDatabase.setDatabaseName(dataBaseString);mDatabase.open(); mRequete = new QSqlQuery(); mRequete->prepare("SELECT Numero, Nom FROM Compte WHERE Numero > 10 and Numero < 25");
mRequete->exec();
sqlModele = new QSqlTableModel;
sqlModele->setQuery(*mRequete);ui->tableView->setModel(sqlModele);
ui->tableView->show();
}
monmodele.h
#ifndef MONMODELE_H
#define MONMODELE_H#include <QObject>
#include <QAbstractTableModel>
#include <QColor>class monModele : public QAbstractTableModel
{public:
monModele(QObject *parent = 0); QVariant data ( const QModelIndex & index, int role)const;
private:
};
#endif // MONMODELE_H
monmodele.cpp
#include "monmodele.h"
#include <QSqlTableModel>monModele::monModele(QObject *parent) : QAbstractTableModel(parent) { } QVariant monModele::data ( const QModelIndex & index, int role)const { if(role==Qt::BackgroundColorRole) { const QVariant value(data(index,Qt::DisplayRole)); return QVariant(QColor(Qt::red)); } return monModele::data(index,role); }
-
@lacombe
Not in answer to your question, but:QVariant monModele::data ( const QModelIndex & index, int role)const { ... return monModele::data(index,role); }
That's infinite recursion! You'll want something more like
return QAbstractTableModel::data(index,role);
-
You can use "Role Mask Proxy Model" from https://github.com/VSRonin/QtModelUtilities/tree/dev You can find an example of colouring the background here: https://github.com/VSRonin/QtModelUtilities/blob/dev/examples/exem_RoleMaskProxyModel/exem_rolemaskhighlight.cpp
I'm also trying to get it merged into Qt itself: https://codereview.qt-project.org/245572/