Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to rename column headers in Table View?



  • Hi guys. I met a problem when I wanted to rename my column headers. I used Table view.

    My re-implemented headerData and setHeaderData in tablemodel.cpp look like below:

    QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const
    {
        if (role != Qt::DisplayRole)
            return QVariant();
     
       if (orientation == Qt::Horizontal){
            //qDebug()<<headerdata.at(section);
            return headerdata.at(section);
        }
        return QVariant();
    }
     
    bool TableModel::setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role)
    {
        if (section < headerdata.size() && role == Qt::EditRole)
        {
            headerdata.replace(section, value.toString());
            //qDebug()<<section;
            emit headerDataChanged(orientation,section,section);
            return true;
        }
        return false;
    }
    

    Is there anything wrong? Or if it's not wrong, why I can't edit columns header?
    What I want is that the headers can be editable like other data, i.e. click one column header then type then press return then it will update.

    Please help me. Thanks in advance! :)


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    What model are you subclassing ?
    What version of Qt are you using ?
    On what OS ?

    Can you provide a minimal compilable example that shows that behaviour ?



  • @soleyran said in How to rename column headers in Table View?:

    Is there anything wrong?

    No

    why I can't edit columns header?

    Because QHeaderView doesn't have an "edit mode". It's a feature you have to implement yourself



  • @vronin Thank you! You are right, I made it after implementing myself. But I have another question coming... I post it under this topic, please have a look :)



  • I was using Dialog to get the text of new header, then call setHeaderData() to change the header. The process was Right click on a header->Rename header->Open a dialog. It looks like below:
    0_1564605120383_Screenshot (2).png
    0_1564605125995_Screenshot (3).png

    It works, but what I want is that it can be changed right in the column header, which will look like this:
    0_1564605141029_renamecolumn.gif

    I think it maybe done by changing the column header to a text edit box via a delegate, but I have no idea...

    Can anyone help? Thanks a lot :)



  • QHeaderView does not use delegates unfortunately. The solution I'd suggest is to have a QLineEdit widget spawn on top of the header to do the editing rather than spawning a dialog