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 an开发者_JAVA技巧d 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();
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
}
精彩评论