Question

My custom table model derives from QAbstractTableModel and is then displayed in a QTableView.

Looks like this:

enter image description here

I would like to change the text color for certain row headers, which can be decided in the model. Is it possible to color certain headers from there? I couldn't find a way so far. What I found was about setting background/text color for all headers, not for special few. The color is supposed to be kind of markup for the user.

Was it helpful?

Solution

What you have to do is reimplement QAbstractTableModel::headerData(). Depending on the value of section (header index starting at zero) you can individually style the header items. The relevant values for foreground (=text color) and background in Qt::ItemDataRole are Qt::BackgroundRole and Qt::ForegrondRole

E.g. like this:

QVariant MyTableModel::headerData(int section, Qt::Orientation orientation, int role) const {
  //make all odd horizontal header items black background with white text
  //for even ones just keep the default background and make text red
  if (orientation == Qt::Horizontal) {
    if (role == Qt::ForegroundRole) {
       if (section % 2 == 0)
          return Qt::red;
       else
         return Qt::white;
    }
    else if (role == Qt::BackgroundRole) {
       if (section % 2 == 0)
          return QVariant();
       else
         return Qt::black;
    }
    else if (...) {
      ...
      // handle other roles e.g. Qt::DisplayRole
      ...
    }
    else {
      //nothing special -> use default values
      return QVariant();
    }
  }
  else if (orientation == Qt::Vertical) {
      ...
      // handle the vertical header items
      ...
  }
  return QVariant();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top