在 Qt 中,QTableView 是一个用于展示表格数据的控件。如果你想要处理行选择事件,你可以通过连接 QTableView 的 selectionModel() 返回的 QItemSelectionModel 对象的信号来实现。通常,你会对 selectionChanged 信号感兴趣,这个信号在用户选择或取消选择表格中的项时触发。
以下是一个处理 QTableView 行选择事件的基本示例:
#include <QApplication>
#include <QTableView>
#include <QStandardItemModel>
#include <QItemSelectionModel>
#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).arg(column));
}
}
// 创建表格视图并设置模型
QTableView tableView;
tableView.setModel(&model);
// 连接选择模型的选择变化信号
QObject::connect(tableView.selectionModel(), &QItemSelectionModel::selectionChanged,
[&](const QItemSelection &selected, const QItemSelection &deselected){
// 当选择变化时,此函数将被调用
QModelIndexList indexes = selected.indexes();
if (!indexes.isEmpty()) {
QModelIndex firstIndex = indexes.first();
qDebug() << "Row selected:" << firstIndex.row();
}
});
tableView.show();
return app.exec();
}
在这个例子中,我们首先创建了一个 QStandardItemModel 并填充了一些数据。然后,我们创建了一个 QTableView 并将其模型设置为之前创建的模型。接下来,我们连接了 QTableView 的 selectionModel() 返回的 QItemSelectionModel 对象的 selectionChanged 信号到一个 lambda 函数。这个 lambda 函数在每次选择变化时被调用,并打印出被选中的第一行的行号。
请注意,这个示例仅用于演示目的,并可能需要根据你的具体需求进行调整。例如,如果你想要处理多行选择或获取更多关于所选项的信息,你可能需要遍历 indexes 列表并处理每个 QModelIndex。
4937

被折叠的 条评论
为什么被折叠?



