PDA

View Full Version : How to set header in Table View?



SoleyRan
29th July 2019, 22:18
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! :)

d_stranz
30th July 2019, 17:50
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.

SoleyRan
31st July 2019, 21:23
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:
13215
13216

It works, but what I want is that it can be changed right in the column header, which will look like this:
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:)

d_stranz
1st August 2019, 23:56
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 (https://doc.qt.io/qt-5/modelview.html) or from your friend Google.