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);
}
相关推荐
老刘忙Giser几秒前
c# List<string>.Add(s) 报错:UnsupportedOperationException
开发语言·c#
itwlz9 分钟前
vite配置@别名,以及如何让IDE智能提示路经
开发语言·前端·javascript
lichenyang45311 分钟前
添加按钮跳转页面并且根据网站的用户状态判断是否显示按钮
开发语言·前端·javascript
誰能久伴不乏15 分钟前
Qt 开发中的父类与父对象的区别和父对象传递:如何选择 `QWidget` 或 `QObject`?
java·开发语言·qt
弱冠少年16 分钟前
golang入门
开发语言·后端·golang
Humbunklung19 分钟前
Rust 函数
开发语言·后端·rust
waterHBO21 分钟前
python 爬虫工具 mitmproxy, 几问几答,记录一下
开发语言·爬虫·python
誰能久伴不乏30 分钟前
理解继承与组合的本质:Qt 项目中的设计选择指南
开发语言·qt
chicpopoo44 分钟前
Python打卡DAY46
开发语言·python
灏瀚星空1 小时前
Python数学可视化:3D参数曲面与隐式曲面绘制技术
开发语言·python·3d