【问题标题】:Qt: Accessing cells in a QTableViewQt:访问 QTableView 中的单元格
【发布时间】:2010-08-21 22:25:47
【问题描述】:

我有一个 QTableView,它从 SQLite 数据库中提取位置列表和纬度/经度坐标。我想从用户在表中选择的行中提取纬度和经度,并且正在使用以下代码,但它看起来相当复杂。也许我只是不了解如何充分利用 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();

【问题讨论】:

    标签: qt model-view


    【解决方案1】:

    我假设您的表格如下所示:

    +--------+--------+---------+ |位置|纬度|经度| +--------+--------+---------+ |一个 | 11'.22"| 11'.22" | +--------+--------+---------+

    从上面的代码中可以看出,我得出的结论是,您希望您的用户一次选择一整行。 如果是这样,我建议您在 QTableView 上设置以下属性:

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

    然后我会 connect()selectionChanged 选择模型的信号:

    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
    }
    

    【讨论】:

    • 模型是数据的来源。你说你从 SQLite 数据库提供你的 QTableView,所以这可能是QSqlTableModelQSqlRelationalTableModel 的一个实例。基本上它是你传递给ui->tableView->setModel() 的唯一参数。
    • 啊,当然! QSqlTableModel,是的。感谢您的帮助,很抱歉延迟接受。我的代码现在看起来干净多了。
    猜你喜欢
    • 2011-05-13
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多