Setting background color to a whole table column including header item

  • Hi,
    I've got a QListWidget that contains the horizontal header contents of a QTableWidget.
    When user selects (clicks) on one of those items in the QListWidget, I'd like to enhance the whole column that has the clicked header item.
    My idea was to do it in a loop and set a background-color to every table cell, but there are two problems:

    1. I don't know how to enhance the header item
    2. each table cell contains a full-sized QWidget with a checkbox within. So what I need to do is setting a background-color to the QWidget within, right? How can I do that? Also I would have to make the checkbox text transparent, so there is no white container around it...

    Does anyone have a solution for that?

  • Well, my first try was to add QTableWidgetItems to the horizontal header and then using setBackground:
    @for(int i = 0; i < this->table->columnCount(); i++)
    QTableWidgetItem* item = new QTableWidgetItem();
    item->setText("Column "+QString::number(i));
    this->table->setHorizontalHeaderItem(i, item);
    The interesting thing is, setting text color via setForeground(..) works well to each header item, but setting background color via setBackground(..) has no effect... why?

  • Hi,

    To do that, I would have create a method in the model called something like setCurrentColumn(const QModelIndex& index) and a private int called, let's say m_currentColumn.

    Make sure in your data() and headerData() method that you take m_currentColumn in account to render a different background color (using BackgroundRole).

    Now, in your method setCurrentColumn(), you emit the dataChanged signal to indicate the BackgroundRole change for all the row of the column m_currentColumn. Do the same with headerDataChanged().
    Then, update m_currentColumn to the new column (using the index pass as argument) and emit again the signal dataChanged() and headerDataChanged() using the new value of m_currentColumn.

    By the way, do you known the model handle by itself checkable elements? See Qt::ItemIsUserCheckable flag.

    Hope it helps.

  • Hm, sorry but I do not understand how you set a specific background color via setBackgroundRole(QPallete::ColorRole); ... When I take a look at the documentation, ColorRoles are stuff like "Window", "WindowText", "Base" etc... but I'm looking for something to define the specific color like QColor(255,0,0)... how do I manage this?

  • @
    QVariant data(const QModelIndex& index, int role)
    if (index.isValid() && index.row() < rowCount())
    // ...

        if (index.column() == m_currentColumn && role == Qt::BackgroundColor)
            return QColor(255, 0, 0);


Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.