How to get list of headers of a QTableView?
Asked Answered
W

2

9

I have a QTableView object in my dialog.

I need to access the horizontal headers of this table and put them into a QStringList object.

Despite intensive search, I could not find in Qt documentation how to get this list of headers.

Edit: The closest I've found anywhere is this, but it's dealing with QTableWidget, and the functions used aren't available for QTableView. Unfortunately, I'm not at liberty to switch the object in question to a table widget.

Windstorm answered 8/4, 2014 at 18:1 Comment(0)
W
22

So, the only way I can figure out to do it as like this:

QStringList headers;
for(int i = 0; i < myTableView->model()->columnCount(); i++)
{
  headers.append(myTableView->model()->headerData(i, Qt::Horizontal).toString());
}

Honestly this still seems a lot more convoluted than it should have to be, but at least it works.

Windstorm answered 8/4, 2014 at 18:17 Comment(2)
I think "a lot more convoluted than it should have to be" is the official motto of Qt's ItemView classes ;)Profanity
@JeremyFriesner haha I feel the exact same way, ListView isn't too bad but TableView is such a pain, and that's nothing compared to the TreeViewWindstorm
A
3

You can simplify it a bit, like so. this is the python variation

items = []
for x in range(tbl.columnCount()):
    items.append(tbl.horizontalHeaderItem(x).text())
Astray answered 3/2, 2022 at 0:13 Comment(1)
I had to use tbl.horizontalHeaderItem(x)->text() in C++Elly

© 2022 - 2024 — McMap. All rights reserved.