Please nominate your Qt Champions for 2021!

Instantely updateing headerData of QItemModel (QTreeView) when changing selection

  • Hello,
    i have a QTreeView with differnt sorts of members in each row and therefore want to change the desctiption in the header according to the current selection.

    What i have come up with is following:

    QVariant TreeModel::headerData(int section, Qt::Orientation orientation, int role) const {
        if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
            QModelIndex index = m_tree_view->currentIndex();
            TreeItem* Item_selected = static_cast<TreeItem*>(index.internalPointer());
            std::string value;
            if(Item_selected != 0) {
                value = Item_selected->getDispName(section);
            } else{
                value = m_root_item->getDispName(section);
            return QVariant(value.c_str());
        return QVariant();
    This works fine, however it often tankes some time till the headers get updated, (mouseover helps, but sometimes works without)
    Is there a way to re-draw the header instantainiously?

  • Hi,

    Do you emit the signal QAbstractItemModel::headerDataChanged() when you change your header datas?

    The documentation says: "When reimplementing the setHeaderData() function, this signal must be emitted explicitly."
    -> documentation of QAbstractItemModel::headerDataChanged.


    Basically what you are doing is evil.

    You should connect m_tree_view->selectionModel()'s currentIndexChanged() signal with a slot that calls setHeaderData in the model. that's all