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
andsetHeaderData
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! :)
-
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 -
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:
It works, but what I want is that it can be changed right in the column header, which will look like this:
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 aQLineEdit
widget spawn on top of the header to do the editing rather than spawning a dialog
1/6