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);
}
相关推荐
moxiaoran5753几秒前
Go语言的接口
开发语言·后端·golang
浮尘笔记12 分钟前
Go语言中的同步等待组和单例模式:sync.WaitGroup和sync.Once
开发语言·后端·单例模式·golang
lsx20240615 分钟前
C++ 变量作用域
开发语言
小鸡脚来咯20 分钟前
设计模式面试介绍指南
java·开发语言·单例模式
小北方城市网20 分钟前
GEO 全场景智能生态:自适应架构重构与极限算力协同落地
开发语言·人工智能·python·重构·架构·量子计算
十五年专注C++开发28 分钟前
CMake进阶:核心命令get_filename_component 完全详解
开发语言·c++·cmake·跨平台编译
Blossom.11829 分钟前
工业级扩散模型优化实战:从Stable Diffusion到LCM的毫秒级生成
开发语言·人工智能·python·深度学习·机器学习·stable diffusion·transformer
嘿嘿潶黑黑30 分钟前
关于QButtonGroup 在Qt5和Qt6之间的差异
开发语言·qt
代码游侠30 分钟前
应用——Linux FrameBuffer图形显示与多线程消息系统项目
linux·运维·服务器·开发语言·前端·算法
hqwest31 分钟前
码上通QT实战09--监控页面01-区域划分
开发语言·qt·layout·qss·qt 布局