qt的QItemSelectionModel

先在界面上来个表格,在工具栏上增加两个工具按钮

cpp 复制代码
	QStandardItemModel * model = new QStandardItemModel(7, 4, this);
	for (int row = 0; row < 7; row++) {
		for (int column = 0; column < 4; column++) {
			QStandardItem * item = new QStandardItem(QString("%1").arg(row * 4 + column));
			model->setItem(row, column, item);
		}
	}
	_table_view = new QTableView;
	_table_view->setModel(model);
	setCentralWidget(_table_view);
	this->resize(800, 800);

	//获取视图的项目选择模型
	QItemSelectionModel * selection_model = _table_view->selectionModel();
	
	ui.mainToolBar->addAction(tr(u8"当前项目"), this, &QtWidgetsApplication7::getCurrentItemData);
	ui.mainToolBar->addAction(tr(u8"切换选择"), this, &QtWidgetsApplication7::toggleSelection);

接下来是实现这两个函数

cpp 复制代码
void QtWidgetsApplication7::getCurrentItemData()
{
	auto currentData = _table_view->selectionModel()->currentIndex().data().toString();
	qDebug() << tr(u8"当前项目的内容") << currentData;
}

void QtWidgetsApplication7::toggleSelection()
{
	//找到根节点下第0行0列的item的索引
	QModelIndex topLeft = _table_view->model()->index(0, 0, QModelIndex());
	//获取根节点下最大的行号
	auto max_row = _table_view->model()->rowCount(QModelIndex());
	//获取根节点下最大的列号
	auto max_column = _table_view->model()->columnCount(QModelIndex());
	//根据列号和行号获取最右下角的item的索引
	QModelIndex bottomRight = _table_view->model()->index(max_row - 1, max_column - 1, QModelIndex());
	//设置选择区域
	QItemSelection curSelection(topLeft, bottomRight);
	_table_view->selectionModel()->select(curSelection, QItemSelectionModel::Toggle);
}
相关推荐
兮兮能吃能睡35 分钟前
资料片:R语言中常见的英文术语及其含义
开发语言·r语言
zz-zjx41 分钟前
JVM垃圾收集器详解(jdk21+25实战版)
java·开发语言·jvm
郝学胜-神的一滴1 小时前
Linux系统函数link、unlink与dentry的关系及使用注意事项
linux·运维·服务器·开发语言·前端·c++
赵杰伦cpp1 小时前
list的迭代器
开发语言·数据结构·c++·算法·链表·list
_extraordinary_2 小时前
Java Spring配置
java·开发语言·spring
进击的大海贼2 小时前
QT-C++ 自定义加工统计通用模块
开发语言·c++·qt
Rhys..2 小时前
JS - npm init
开发语言·javascript·npm
newxtc2 小时前
【 广州产权交易所-注册安全分析报告-无验证方式导致安全隐患】
开发语言·人工智能·selenium·安全·yolo
兩尛2 小时前
java八股-操作系统
java·开发语言
wjs20243 小时前
SQL 日期处理指南
开发语言