QTableView 获取选中行的下标

要点

// 假设是单行选择模式,我们只需要第一个索引的行号  
                int row = indexes.first().row();

正文

在 Qt 中,若您想从 QTableView 获取选中行的下标(即行号),您可以通过监听 QItemSelectionModel 的 selectionChanged 信号来实现。当用户选中或取消选中某行时,这个信号会被触发。以下是一个简单的示例,说明如何在用户选中行时获取其下标:

 
#include <QApplication>  
#include <QTableView>  
#include <QStandardItemModel>  
#include <QDebug>  
  
int main(int argc, char *argv[]) {  
    QApplication app(argc, argv);  
  
    // 创建一个标准的表格模型并填充数据  
    QStandardItemModel model(5, 3); // 5行3列  
    for (int row = 0; row < 5; ++row) {  
        for (int column = 0; column < 3; ++column) {  
            QModelIndex index = model.index(row, column);  
            model.setData(index, QString("Item %1-%2").arg(row + 1).arg(column + 1));  
        }  
    }  
  
    // 创建表格视图并设置模型  
    QTableView tableView;  
    tableView.setModel(&model);  
    tableView.setSelectionMode(QAbstractItemView::SingleSelection);  
    tableView.setSelectionBehavior(QAbstractItemView::SelectRows);  
  
    // 获取选择模型  
    QItemSelectionModel *selectionModel = tableView.selectionModel();  
  
    // 连接选择变化信号  
    QObject::connect(selectionModel, &QItemSelectionModel::selectionChanged,  
        [&](const QItemSelection &selected, const QItemSelection &deselected){  
            // 获取选中的索引  
            QModelIndexList indexes = selectionModel->selectedIndexes();  
            if (!indexes.isEmpty()) {  
                // 假设是单行选择模式,我们只需要第一个索引的行号  
                int row = indexes.first().row();  
                qDebug() << "Selected row index:" << row;  
            }  
        });  
  
    tableView.show();  
    return app.exec();  
}

在这个示例中,当用户选中 QTableView 中的某一行时,selectionChanged 信号会被触发,然后槽函数会执行。在槽函数中,我们通过 selectionModel->selectedIndexes() 获取当前选中的所有索引,由于我们设置了单行选择模式,所以只需要取第一个索引的行号即可。这个行号就是通过 QModelIndex::row() 方法获得的选中行的下标。

请注意,这个示例假设您已经正确设置了 Qt 环境和项目配置,并且包含了必要的 Qt 模块头文件。如果您在实际应用中遇到问题,请确保您的项目设置正确。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值