4

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.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Ugurcan
  • 366
  • 1
  • 4
  • 17

1 Answers1

7

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.

alec
  • 5,799
  • 1
  • 7
  • 20
  • AttributeError: 'NoneType' object has no attribute 'text'. – Ugurcan Mar 19 '20 at 04:51
  • @Ugurcan That's probably because there was no vertical header in a particular row. I edited the answer – alec Mar 19 '20 at 04:58
  • Thank you. I am new at PyQT and QT. It worked. ´columns = set(cell.column() for cell in self.table.selectedIndexes()) # set to remove duplicates, otherwise use a list labels = [self.table.horizontalHeaderItem(c).text() for c in columns]´ – Ugurcan Mar 19 '20 at 05:10