Set color to a QTableView row

前端 未结 2 1859
无人及你
无人及你 2020-12-09 11:58
void MyWindow::initializeModelBySQL(QSqlQueryModel *model,QTableView *table,QString sql){
        model = new QSqlQueryModel(this);
        model->setQuery(sql);
         


        
2条回答
  •  北海茫月
    2020-12-09 12:32

    Your best bet is to define a custom model (QAbstractTableModel subclass). You probably want to have a QSqlQueryModel as a member in this custom class.

    If it's a read-only model, you need to implement at least these methods:

     int rowCount(const QModelIndex &parent) const;
     int columnCount(const QModelIndex &parent) const;
     QVariant data(const QModelIndex &index, int role) const;
    

    and for well behaved models also

     QVariant headerData(int section, Qt::Orientation orientation, int role) const;
    

    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:

     Qt::ItemFlags flags(const QModelIndex &index) const;
     bool setData(const QModelIndex &index, const QVariant &value, int role=Qt::EditRole);
     bool insertRows(int position, int rows, const QModelIndex &index=QModelIndex());
     bool removeRows(int position, int rows, const QModelIndex &index=QModelIndex()); 
    

    What will actually change a row appearance lies in the return value of this method:

     QVariant data(const QModelIndex &index, int role) const;
    

    A dumb example:

     QVariant MyCustomModel::data(const QModelIndex &index, int role) const
     {
         if ( !index.isValid() )
             return QVariant();
    
         int row = index.row();
         int col = index.column();
    
    
         switch ( role )
         {
    
            case Qt::BackgroundRole:
            {
                if(somecondition){
                   // background for this row,col is blue
                   return QVariant(QBrush (QColor(Qt::blue)));
                }
                // otherwise background is white
                return QVariant(QBrush (QColor(Qt::white)));
            }
    
            case Qt::DisplayRole:
            {
               // return actual content for row,col here, ie. text, numbers
    
            }
    
            case Qt::TextAlignmentRole:
            {
    
               if (1==col)
                  return QVariant ( Qt::AlignVCenter | Qt::AlignLeft );
    
               if (2==col)
                  return QVariant ( Qt::AlignVCenter | Qt::AlignTrailing );
    
               return QVariant ( Qt::AlignVCenter | Qt::AlignHCenter );
    
            }
         }
    
      }
    

提交回复
热议问题