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);
}
相关推荐
xcs194051 分钟前
Java 上位机防空警报系统开发
java·开发语言
追光的蜗牛丿12 分钟前
C++中引用与指针的选择
开发语言·c++
Three~stone12 分钟前
MATLAB vs Python 两者区别和安装教程
开发语言·python·matlab
soragui23 分钟前
【Python】第 1 章:Python 解释器原理
开发语言·python
UAq6wn76j29 分钟前
.NET源码生成器使用SyntaxTree生成代码及简化语法
java·开发语言·.net
@atweiwei31 分钟前
Go语言并发编程面试题精讲(上)
java·开发语言·面试·golang·channel
不会写DN32 分钟前
使用 sync.Once 解决 Go 并发场景下的重复下线广播问题
开发语言·网络·golang
_MyFavorite_36 分钟前
JAVA重点基础、进阶知识及易错点总结(36)Lombok 实战 + 阶段总结
java·开发语言
xyq20241 小时前
过滤器模式
开发语言
freejackman1 小时前
Java从0到1---基础篇
java·开发语言·后端·idea