Thursday, May 17, 2018

Did the Hightlighted row in a TableView change?

Seems like this would be one of the basic things you'd want to know about a TableView.
Granted the Qt TableView is insanely complex because it implements most of the functionality of a spreadsheet.
Maybe they should have had a simpler TableView and a TableEditor class.
Regardless, I am using a TableView as a fancy list display where you can sort on different columns and "select" the whole row.

So confusing point number one is that a TableView has a "current index" and a "selection" and they are not necessarily the same.

For example, this code changes both at once:

tableview->setCurrentIndex (index);

But this code, which appears to work, leaves a light blue "current index" indicator on the previously selected row if you sort the tableView first.

tableView->selectionModel()->select (index, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);

As you can see from the above code, there are 2 levels to the API. This is annoying and confusing to say the least. Many operations can be done directly on the TableView, while others can only be done on the TableView's selection model. As shown above sometimes you can perform the operation on both, but with different results.

So back to the topic. I want to know what a row in my table is selected. Either when I user clicks on it with the mouse, or by using the cursor keys to run up and down the list.
I can do this to get clicks or double clicks:

void ActionList::on_tableView_clicked (QModelIndex index)

void ActionList::on_tableView_doubleClicked (QModelIndex index)
Usual Qt magic applies and if I get the name right these slots will automatically be connected. Kind of nice. Unfortunately, there is no selectionChanged signal on the TableView. There is one on the TableView's selection Model, but since it is an automatically created object whose name is "", you can't use the moc naming trick. Instead, you get to use this delight:

     connect (tableView->selectionModel(),
     SIGNAL (selectionChanged (const QItemSelection &, const QItemSelection &)),
     SLOT(selectionChanged (const QItemSelection &, const QItemSelection &)));
 At least it works, but it really should not be that convoluted.

No comments:

Post a Comment