0

SQLiteデータベースから場所と緯度/経度の座標のリストを取得しているQTableViewがあります。ユーザーがテーブルで選択した行から緯度と経度を抽出し、次のコードを使用していますが、かなり複雑に見えます。Qtのモデル/ビューシステムを十分に活用する方法がわからないのかもしれません。このコードをより明確でコンパクトな方法で記述できますか?

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();
4

1 に答える 1

4

私はあなたのテーブルがこのように見えると思います:

+ -------- + -------- + --------- +
|場所|緯度|経度|
+ -------- + -------- + --------- +
| A | 11'.22 "| 11'.22" |
+ -------- + -------- + --------- +

上記のコードからわかるように、ユーザーが一度に1行全体を選択するようにしたいという結論に達しました。その場合は、次のプロパティを設定することをお勧めしますQTableView

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

次に、選択モデルのselectionChangedシグナルを実行しますconnect()

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

スロットの実装は次のとおりです。

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
}
于 2010-08-21T23:18:49.147 に答える