3

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?

sashoalm
  • 75,001
  • 122
  • 434
  • 781

5 Answers5

3

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 )

Najzero
  • 3,164
  • 18
  • 18
  • 1
    I guess using `currentColumnChanged()` would be the most efficient. – sashoalm Mar 22 '13 at 08:31
  • most deffinatly, just keep in mind if your code sets the column somewhere the signal gets fired too ( afaik only qts `reset()` does not fire that signal) – Najzero Mar 22 '13 at 08:33
1
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
}
Lwin Htoo Ko
  • 2,326
  • 4
  • 26
  • 38
1
connect(tableWidget->selectionModel()
        , SIGNAL(currentColumnChanged(QModelIndex,QModelIndex))
        , SLOT(onColumnChanged(QModelIndex)));

...

void Class::onColumnChanged(const QModelIndex &index)
{
    int col = index.column();
}
Amartel
  • 4,248
  • 2
  • 15
  • 21
0

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();
sashoalm
  • 75,001
  • 122
  • 434
  • 781
0

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

movildima
  • 37
  • 1
  • 9