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);
}
相关推荐
瓦特what?8 分钟前
关于C++的#include的超超超详细讲解
java·开发语言·数据结构·c++·算法·信息可视化·数据挖掘
祁同伟.41 分钟前
【C++】动态内存管理
开发语言·c++
一只鲲1 小时前
40 C++ STL模板库9-容器2-vector
开发语言·c++
励志不掉头发的内向程序员1 小时前
C++基础——内存管理
开发语言·c++
lifallen1 小时前
JCTools 无锁并发队列基础:ConcurrentCircularArrayQueue
java·开发语言·数据结构·算法
千里镜宵烛2 小时前
深入理解 Linux 线程:从概念到虚拟地址空间的全面解析
开发语言·c++·操作系统·线程
Eternity_GQM2 小时前
【Word VBA Zotero 引用宏错误分析与改正指南】【解决[21–23]参考文献格式插入超链接问题】
开发语言·c#·word
张柏慈2 小时前
JavaScript性能优化30招
开发语言·javascript·性能优化
promising-w3 小时前
【嵌入式C语言】六
c语言·开发语言
打不了嗝 ᥬ᭄3 小时前
Linux 信号
linux·开发语言·c++·算法