March 29, 2011

poporacer poporacer
Lab Rat
59 posts

set background color to a cell of a tableView

Page  
1

I have a tableview that is using a QSqlRelationalTableModel. The table view has a column that I want to color the cell (or row) with the highest sales total (column 5). I can iterate through the model and get the row that the highest value is in. I have tried several methods to color the cell to no avail. I have read that it can be done with a custom proxy or delegate but no samples of code so I am not sure what they mean. From what I have read, the following should work.

  1.  printModel= new QSqlRelationalTableModel (this);
  2.     printModel-> setEditStrategy(QSqlTableModel::OnRowChange);
  3.     printModel-> setTable (mTableName);
  4.  
  5.     printModel-> setRelation (2, QSqlRelation("customer", "id", "Name"));
  6.     printModel->select();
  7.  
  8.    QAbstractItemModel *model = ui->printView->model();
  9.    QModelIndex modelIdx = model->index(rowHighSales, 5, QModelIndex()); //rowHighSales is the row with the highest sales
  10.    model->setData(modelIdx, yellow, Qt::BackgroundRole); //this returns false if I use debug.  red is a QBrush

Can this work or is there a better way to do it?

Thanks

53 replies

March 29, 2011

ZapB ZapB
Robot Herder
1359 posts

I’m not sure. You would need to look at the source for QSqlRelationalTableModel::setData() to see how it handles the background role – I suspect it doesn’t support it.

If that is the case a simple approach would be to use a very simple proxy model that returns the correct background color in the data() function.

 Signature 

Nokia Certified Qt Specialist
Interested in hearing about Qt related work

March 29, 2011

Gerolf Gerolf
Area 51 Engineer
3213 posts

Using a simple proxy model or a delegate is the safe way of doing it.
I, personally, would like to use a proxy model, derived from QSortFilterProxyModel.
You only have to overwrite data() and return the correct color if needed. In all other cases, you just call the default impl.

 Signature 

Nokia Certified Qt Specialist.
Programming Is Like Sex: One mistake and you have to support it for the rest of your life. (Michael Sinz)

March 29, 2011

ZapB ZapB
Robot Herder
1359 posts

Agreed, plus you also get all the nice features of QSFPM too so you could even sort on yoru column too if you like.

 Signature 

Nokia Certified Qt Specialist
Interested in hearing about Qt related work

March 29, 2011

Andre Andre
Area 51 Engineer
6076 posts

Yes, indeed, a proxy model is the way to go.

What you do is that you subclass QSortFilterProxyModel, and reimplement the data() method to return the source data for the DisplayRole and the EditRole, and returns your color for the BackgroundRole when asked for it.

I have written a generic proxy model that basically just overlays an existing table-type model (that is: it doesn’t work on trees, only on a specific level of one). The overlay model supplies one set of roles, while the underlying model supplies the rest. You can use setData() on it to set data on all roles, and it will either store the value in the overlay model or forward the call to the source model. You can also use it to adjust flags. You could use a setup like that to set your color like you do now, but store it in your own “overlay model” instead of in the QSqlRelationalTableModel. It is not very hard to implement.

 Signature 

Looking for Qt developers to join our team @ i-Optics: https://qt-project.org/forums/viewthread/25393/

March 29, 2011

poporacer poporacer
Lab Rat
59 posts

Ok, as I am new to all this, I am not sure how to use a proxy model, derived from QSortFilterProxyModel. Could you give me some code to get me started? I will research this as well, but from reading the docs, I am not sure how to do what you recommend. Thanks

March 29, 2011

Gerolf Gerolf
Area 51 Engineer
3213 posts

You could start reading the docs [doc.qt.nokia.com] , they are really good.

 Signature 

Nokia Certified Qt Specialist.
Programming Is Like Sex: One mistake and you have to support it for the rest of your life. (Michael Sinz)

March 30, 2011

poporacer poporacer
Lab Rat
59 posts

Ok so I re read the docs, and searched, but couldn’t get it to work. Here is what I have….where did I go wrong? In setting up the table I use

  1.    QSortFilterProxyModel *printModel = new QSortFilterProxyModel(parent);
  2.    printModel->setSourceModel(myModel);
  3.    ui->printView->setModel(printModel);

and I get an error: cannot declare variable ‘myModel’ to be of abstract type ‘QAbstractItemModel’ because the following virtual functions are pure within ‘QAbstractItemModel’: virtual QModelIndex QAbstractItemModel::index(int, int, const QModelIndex&) const .(and many more)
I think I have to add something else…how and what do I need to do? I copied the code almost exactly.

March 30, 2011

Gerolf Gerolf
Area 51 Engineer
3213 posts

It tells you what is wrong, QAbstractItemModel is not creatable. It is the abstract base class of all Models, and it is ABSTRACT. you normally go this way:

  1.    printModel= new QSqlRelationalTableModel (this);
  2.    printModel-> setEditStrategy(QSqlTableModel::OnRowChange);
  3.    printModel-> setTable (mTableName);
  4.  
  5.    printModel-> setRelation (2, QSqlRelation("customer", "id", "Name"));
  6.    printModel->select();
  7.  
  8.    MyQSFPM* proxy = new MyQSFPM(this);
  9.    proxy->setSourceModel(printModel);
  10.    ui->printView->setModel(proxy);

now you have to create MyQSFPM as derived class of QSortFilterProxyModel abd reimplement data.

  1. class MyQSFPM : public QSortFilterProxyModel
  2. {
  3.     ...
  4. }

 Signature 

Nokia Certified Qt Specialist.
Programming Is Like Sex: One mistake and you have to support it for the rest of your life. (Michael Sinz)

March 31, 2011

poporacer poporacer
Lab Rat
59 posts

I feel stupid. I have read several docs and searched and still do not understand how to reimplement the data in the derived class. Do I simply copy the implementation of the functions I need to use and put them in the derived class? I am going to continue reading and trying things. Sorry for not understanding.

March 31, 2011

Gerolf Gerolf
Area 51 Engineer
3213 posts

Hi poporacer.

Overwriting methods is standard C++ knowledge.
For more information about model / view, look here:

Qt documentation – Model/View Programming [doc.qt.nokia.com]

 Signature 

Nokia Certified Qt Specialist.
Programming Is Like Sex: One mistake and you have to support it for the rest of your life. (Michael Sinz)

March 31, 2011

Andre Andre
Area 51 Engineer
6076 posts
poporacer wrote:
I feel stupid. I have read several docs and searched and still do not understand how to reimplement the data in the derived class. Do I simply copy the implementation of the functions I need to use and put them in the derived class? I am going to continue reading and trying things. Sorry for not understanding.

As Gerolf points out, overriding virtual methods is a key feature of object oriented programming in C++. It is an essential part of subclassing.

What you need to do in this case, is to handle the cases you want to handle in your reimplementation of data() in your subclass, and use the base implementation for all other cases. Note that it is often a good idea to call the base class implementation of an overridden method in the reimplementation.

In your case, your data method might look something like this*:

  1. QVariant myProxyModel::data ( const QModelIndex & index, int role ) const
  2. {
  3.   if (!index.isValid())
  4.     return QVariant();
  5.  
  6.   QModelIndex sourceIndex = mapToSource( index );
  7.   if ( role == Qt::BackgroundRole ) {
  8.     if (sourceIndex.data( Qt::DisplayRole ).toDouble == m_theValueIWant ) {
  9.       return Qt::red;
  10.     } else {
  11.       return QVariant();
  12.     }
  13.   } else {
  14.     return sourceIndex.data( role );
  15.   }
  16. }

Perhaps that can help you get started.

*) That means: typed in the forum editor, don’t expect this to compile or be complete

Edit: changed sample to return a color, not a checkbox state. I was confused with another question

 Signature 

Looking for Qt developers to join our team @ i-Optics: https://qt-project.org/forums/viewthread/25393/

March 31, 2011

ZapB ZapB
Robot Herder
1359 posts
Andre wrote:
In your case, your data method might look something like this*:

I think you got two threads mixed up, this one is about the background role ;-)

So in this case you reimplementation may look something like:

  1. QVariant myProxyModel::data ( const QModelIndex & index, int role ) const
  2. {
  3.   if (!index.isValid())
  4.     return QVariant();
  5.  
  6.   if ( sourceIndex.row() == m_maxRow && role == Qt::BackgroundRole ) {
  7.     QModelIndex sourceIndex = mapToSource( index );
  8.     return QVariant( Qt::red );
  9.   } else {
  10.     return QSortFilterProxyModel::data( index, role );
  11.   }
  12. }

where m_maxRow is a member variable that you need to set.

 Signature 

Nokia Certified Qt Specialist
Interested in hearing about Qt related work

March 31, 2011

Andre Andre
Area 51 Engineer
6076 posts
ZapB wrote:
Andre wrote:
In your case, your data method might look something like this*:

I think you got two threads mixed up, this one is about the background role ;-)

Yeah, that’s what I just realized. There is another running question on putting checkboxes from an SQL model in a QTableView, and I confused the two. I was already editing my response.

 Signature 

Looking for Qt developers to join our team @ i-Optics: https://qt-project.org/forums/viewthread/25393/

March 31, 2011

ZapB ZapB
Robot Herder
1359 posts

Yeah, I thought so. I’m following that thread too. Easily done ;-)

 Signature 

Nokia Certified Qt Specialist
Interested in hearing about Qt related work

April 4, 2011

poporacer poporacer
Lab Rat
59 posts

I have read the code, read the docs you suggested and yet have not been able to get it to work. I am not sure if I am reading too much into this. So let me explain what I understand that I shoul do so far. I need to create a new class (MyProxyModel) and inherit QSortFilterProxyModel. Then in my class reimplement the data function ( I think that in ZapB’s code the declaration

  1. QModelIndex sourceIndex = mapToSource( index );  

should go at the top of the function?) I am not sure what is meant by having to set m_maxRow is this to the total number of rows or the row number that I want to set the background color? Then in my main class I set up the table following Gerolf’s suggestion. Here is what I have:
myproxymodel.h
  1. #ifndef MYPROXYMODEL_H
  2. #define MYPROXYMODEL_H
  3.  
  4. #include <QSortFilterProxyModel>
  5.  
  6. class MyProxyModel : QSortFilterProxyModel
  7. {
  8.     Q_OBJECT
  9.  
  10. public:
  11.     MyProxyModel();
  12.     ~MyProxyModel();
  13.    QVariant data ( const QModelIndex & index, int role );
  14.    void setSourceModel ( QAbstractItemModel * sourceModel );
  15.  
  16. };
  17. #endif //MYPROXYMODEL_H

myproxymmodel.cpp:

  1. #include "myproxymodel.h"
  2.  
  3. MyProxyModel::MyProxyModel (QObject *parent) :
  4. {
  5.  
  6. }
  7.  
  8. QVariant MyProxyModel::data ( const QModelIndex & index, int role ) const
  9. {
  10.     QModelIndex sourceIndex = mapToSource( index );
  11. if (!index.isValid())
  12.     return QVariant();
  13. if ( sourceIndex.row() == m_maxRow && role == Qt::BackgroundRole )
  14.     {
  15.  
  16.     return QVariant( Qt::red );
  17.     }
  18.     else
  19.     {
  20.     return QSortFilterProxyModel::data( index, role );
  21.     }
  22. }
And in my main class I have
  1. #include "myproxymodel.h"
  2. .
  3. .
  4. .
  5. void MainClass::createReportTable(QStringList stringList)
  6. {
  7.    printModel= new QSqlRelationalTableModel (this);
  8.     printModel-> setEditStrategy(QSqlTableModel::OnRowChange);
  9.     printModel-> setTable (mTableName);
  10.     printModel-> setRelation (2, QSqlRelation("customer", "id", "Name"));
  11.     printModel->select();
  12.     MyProxyModel* proxy = new MyProxyModel(this);
  13.     proxy->setSourceModel(printModel);
  14.     ui->printView->setModel(proxy);

I get several compile errors and I have tried to figure out why, but can’t figure it out.
Line 12 in the main class gives me the error
no matching function for call to ‘MyProxyModel::MyProxyModel(MainClass* const)

Line 14 in the main class gives me the error
‘QAbstractItemModel’ is an inaccessible base of ‘MyProxyModel’

Am I going about this correctly? I am trying to figure it out on my own by “reading the docs” but the docs I have trouble understanding. Where am I going wrong?

In reading, I see this function:
bool QAbstractItemModel::setData ( const QModelIndex & index, const QVariant & value, int role = Qt::EditRole ) [virtual] Is this of any use?

Page  
1

  ‹‹ [SOLVED]Show and use a custom dialog from within a widget or mainwindow      [v4.7.2] Leak with static QMessageBox? ››

You must log in to post a reply. Not a member yet? Register here!