tags:

views:

35

answers:

1

I have a QTableView which is pulling a list of locations and latitude/longitude coordinates from an SQLite database. I want to extract the latitude and longitude from the row that the user has selected in the table, and am using the following code, but it looks fairly convoluted. Maybe I'm just not understanding how to fully utilize Qt's model/view system. Can I write this code in a clearer, more compact way?

QModelIndexList list1 = this->ui->tableView->selectionModel()->selectedRows(1);
QModelIndexList list2 = this->ui->tableView->selectionModel()->selectedRows(2);

if (list1.count() != 1 || (list1.count() != list2.count()))
{
    return;
}

double latitude = list1.at(0).data().toDouble();
double longitude = list2.at(0).data().toDouble();
+2  A: 

I assume your table looks like this:

+--------+--------+---------+
|Location|Latitude|Longitude|
+--------+--------+---------+
|   A    | 11'.22"| 11'.22" |
+--------+--------+---------+

Seen from the code above I conclude that you want your users to select a whole single row at a time. If it is so I'd suggest you to set the following properties on your QTableView:

ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);

Then I'd connect() to selectionChanged signal of the selection model:

connect(ui->tableView, SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &),
        this,          SLOT(onSelectionChanged(const QItemSelection &))));

Here's the implementation of the slot:

void MainWindow::onSelectionChanged(const QItemSelection & selected) {
    // Due to selection mode and behavior settings
    // we can rely on the following:
    // 1. Signal is emited only on selection of a row, not its reset
    // 2. It is emited for the whole selected row
    // 3. Model selection is always valid and non-empty
    // 4. Row indexes of all items in selection match

    int rowIndex = selected.indexes().at(0).row();

    double latitude = model->index(rowIndex, 1).date().toDouble();
    double longitude = model->index(rowIndex, 2).data().toDouble();

    // Do whatever you want with the values obtained above
}
Ihor Kaharlichenko
What is 'model'? There's no index() method on a QItemSelectionModel...
Jake Petroules
Model is the source of your data. You said you feed your QTableView from SQLite database, so probably that is an instance of [QSqlTableModel](http://doc.trolltech.com/latest/qsqltablemodel.html) or [QSqlRelationalTableModel](http://doc.trolltech.com/latest/qsqlrelationaltablemodel.html).Basically it is what you pass to `ui->tableView->setModel()` as the only parameter.
Ihor Kaharlichenko
Ah, of course! An `QSqlTableModel`, yes. Thank you for your help and sorry for the delay in accepting. My code looks much cleaner now.
Jake Petroules