Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get selected header label from QTableWidget item?

I have a QTableWidget item. I fill this item with pandas DataFrame data. I must print selected column values as a report. I can easily print data from DataFrame. However, I need to know verticalHeader (QTableWidget) labels to get data from 'DataFrame'. How can I get selected header labels from QTableWidget?

I tried QTableWidget.selectionModel().selectedIndexes() and QTableWidget.itemFromIndex() method. I could only get items inside of the table not header labels.

Here is my table. I can get items under 'Product No', 'Product Option' and 'List Price (USD)' headers but I can't get these headers.

like image 430
Ugurcan Avatar asked Sep 11 '25 02:09

Ugurcan


1 Answers

You can use QTableWidget.verticalHeaderItem() with the table's current row. If the selected cells are all in the same row, you could do this (table refers to the QTableWidget).

row = table.currentRow()
label = table.verticalHeaderItem(row).text()

Or if cells are selected over multiple rows:

rows = set(cell.row() for cell in table.selectedIndexes()) # set to remove duplicates, otherwise use a list
labels = [table.verticalHeaderItem(r).text() for r in rows]

In the case that a row does not contain a vertical header item, use the text() method only after you've checked that item returned is not None.

headers = [table.verticalHeaderItem(r) for r in rows]
labels = [x.text() for x in headers if x is not None]

Edit: Those are horizontal header items, not vertical. In that case use table.horizontalHeaderItem() instead and get cell columns.

like image 68
alec Avatar answered Sep 13 '25 16:09

alec