QT之QTableView设置选中和获取选中
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QStandardItemModel>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QStandardItemModel* model = new QStandardItemModel(this);
int row = 0;
model->setItem(row, 0, new QStandardItem("ZhangSan"));
model->setItem(row, 1, new QStandardItem("3"));
model->setItem(row, 2, new QStandardItem("male"));
row++;
model->setItem(row, 0, new QStandardItem("ZhangSan1"));
model->setItem(row, 1, new QStandardItem("31"));
model->setItem(row, 2, new QStandardItem("male"));
row++;
model->setItem(row, 0, new QStandardItem("ZhangSan1"));
model->setItem(row, 1, new QStandardItem("31"));
model->setItem(row, 2, new QStandardItem("male"));
row++;
model->setItem(row, 0, new QStandardItem("ZhangSan1"));
model->setItem(row, 1, new QStandardItem("31"));
model->setItem(row, 2, new QStandardItem("male"));
row++;
model->setItem(row, 0, new QStandardItem("ZhangSan1"));
model->setItem(row, 1, new QStandardItem("31"));
model->setItem(row, 2, new QStandardItem("male"));
row++;
ui->tableView->setModel(model);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
ui->tableView->setSelectionMode(QAbstractItemView::SelectionMode::MultiSelection);//开启多选
ui->tableView->selectRow(1);//row_i代表所选行数
ui->tableView->selectRow(3);
ui->tableView->setSelectionMode(QAbstractItemView::SelectionMode::SingleSelection);//恢复单选
}
void MainWindow::on_pushButton_2_clicked()
{
QModelIndexList list = ui->tableView->selectionModel()->selectedIndexes();
qDebug()<<list.count();
for (int i = 0; i < list.count(); i++) {
qDebug() << list[i].row();
}
QModelIndex index = ui->tableView->selectionModel()->currentIndex();
int row = index.row();
qDebug()<<row;
}