Background and icon on tableView

Asked

Viewed 80 times

2

I wonder, how do I add in a tableView to the property of background and icone? I can already add the Background now is missing the icon.

Code:

class tableView : public QSqlTableModel
  {
      Q_OBJECT
      public:
         tableView(QObject * parent = 0, QSqlDatabase db = QSqlDatabase())
         : QSqlTableModel(parent,db) {;}
         QVariant data ( const QModelIndex & index, int role = Qt::DisplayRole ) const
         {
             if(role==Qt::BackgroundColorRole) {
               const QVariant value(data(index,Qt::DisplayRole));
                                  if(value.toString()=="Sim"){
                                      return QVariant(QColor("#d0ffe3")); //<<background 
                                  }else if (value.toString()=="Não"){
                                      return QVariant(QColor("#ffe3d0")); //<<background 
                                  }else if (value.toString()=="Neutro"){
                                      return QVariant(QColor("#fffad0")); //<<background 
                                  }
             }
            return QSqlTableModel::data(index,role);
         }
 };

1 answer

3


When the view requests a Decorationrole, simply return a Qpixmap, which can work either a background image or an icon, or even return a Qicon:

if(role==Qt::BackgroundColorRole) {
   const QVariant value(data(index,Qt::DisplayRole));

   if(value.toString()=="Sim"){
      return QVariant(QColor("#d0ffe3")); //<<background 
   }else if (value.toString()=="Não"){
      return QVariant(QColor("#ffe3d0")); //<<background 
   }else if (value.toString()=="Neutro"){
      return QVariant(QColor("#fffad0")); //<<background 
   }
} elseif (role==Qt::DecorationRole) {
   return QPixmap( "/caminho/pra/imagem/de/teste.jpg" );

   // Depois você vai ter que adaptar ao seu critério de
   // onde vai pegar o icone desejado.
   // Pode usar a mesma lógica do bloco de cima, mas em vez
   // de QColor devolva um QIcon ou QPixmap
}
  • Returns everything in Qvariant? how would this code return all Qpixmap,qicon,qcolor objects?

  • I edited to improve the example

  • OK, thank you very much.

  • @user628298 the function is called several flows. Each time with a different role.

  • Now it worked, but in the second if have to trade Qt::BackgroundColorRole for Qt::DisplayRole. Thank you

  • @user628298 is actually Qt::Decorationrole, I had edited wrong

  • @Bacco You know how to increase icon size?

  • @user628298 Increase to look different from the original image?

  • @Bacco Increases the size of the Qicon in the view. The icon has 32x32, but in the display of the tableView. It appears super small +- 10x10.

  • 1

    @Bacco got it. I was looking in the class QIcon instead of the class QtableView. ui->tableView->setIconSize(QSize(32, 32));

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.