3
votes

I have a QTableWidget with SelectionMode set to SingleSelection, and SelectionBehavior set to SelectColumns. This means that only a single column can be selected.

But I later need to find out which column is selected, and the only functions I can use are selectedIndexes() or selectedItems(), both of which return entire lists, which is wasteful.

Is there a way to do this more efficiently?

5

5 Answers

3
votes

Your approach with the selectedItems() was correct. As QT cant know that you've set your widget to singlerow/column selection it offers those functions to return a QList<>.

in your case you can work on those by using .first().

Evne though I suggest to use the signals currentColumnChanged() to react in your application

( http://harmattan-dev.nokia.com/docs/library/html/qt4/qitemselectionmodel.html#currentColumnChanged )

you could always iterate over all columns of the selected row via selectionModel()->isColumnSelected()

( http://qt-project.org/doc/qt-4.8/qitemselectionmodel.html#isColumnSelected )

1
votes
connect(tableWidget, SIGNAL(currentCellChanged(int,int,int,int), this, SLOT(onCellChanged(int,int,int,int)));

void Class::onCellChanged(int curRow, int curCol, int preRow, int preCol)
{
    current_Col = curCol;
    // curRow, preRow and preCol are unused
}
1
votes
connect(tableWidget->selectionModel()
        , SIGNAL(currentColumnChanged(QModelIndex,QModelIndex))
        , SLOT(onColumnChanged(QModelIndex)));

...

void Class::onColumnChanged(const QModelIndex &index)
{
    int col = index.column();
}
0
votes

It seems that the function selectedRanges() does what I need. It returns a list of the selected ranges, but since it's a single column, this list would have only one item (so it's efficient, no big list need to be created).

int column = ui->tableWidget->selectedRanges().front().leftColumn();
0
votes

currentColumn() returns an int of the current selected column.