How to set header 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:
Code:
QVariant TableModel
::headerData(int section, Qt
::Orientation orientation,
int role
) const {
if (role != Qt::DisplayRole)
if (orientation == Qt::Horizontal){
//qDebug()<<headerdata.at(section);
return headerdata.at(section);
}
}
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! :)
Re: How to set header in Table View?
You probably need to implement the EditRole role for headerData(). You are returning an empty QVariant for everything except DataRole, which is probably telling the header that the cell is not editable.
I don't see anything that corresponds to the flags() method that applies to the header, and QHeaderView does not seem to have anything either to indicate an editable state.
3 Attachment(s)
Re: How to set header in Table View?
Thanks to d_stranz so much! I have made the header editable. But there is a new problem...
I was using Dialog to get the text of new header, then call setHeaderData() to change the header. It looks like below:
Attachment 13215
Attachment 13216
It works, but what I want is that it can be changed right in the column header, which will look like this:
Attachment 13217
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:)
Re: How to set header in Table View?
Quote:
I think it maybe done by changing the column header to a text edit box via a delegate
That is almost certainly what you would do. QHeaderView inherits from QAbstractItemView. The base class allows you to set a delegate for a column (QAbstractItemView::setItemDelegateForColumn() so this might work to allow you to edit the header text in place.
For implementation, you might find some help in the Qt Model / View tutorial or from your friend Google.