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);
}
相关推荐
小禾苗_1 小时前
C++ ——继承
开发语言·c++
李长渊哦1 小时前
Java 虚拟机(JVM)方法区详解
java·开发语言·jvm
进击ing小白1 小时前
Qt程序退出相关资源释放问题
开发语言·qt
烂蜻蜓2 小时前
前端已死?什么是前端
开发语言·前端·javascript·vue.js·uni-app
老猿讲编程2 小时前
安全C语言编码规范概述
c语言·开发语言·安全
OrangeJiuce2 小时前
【QT中的一些高级数据结构,持续更新中...】
数据结构·c++·qt
程序员-King.4 小时前
【接口封装】——13、登录窗口的标题栏内容设置
c++·qt
Biomamba生信基地5 小时前
两天入门R语言,周末开讲
开发语言·r语言·生信
RAN_PAND5 小时前
STL介绍1:vector、pair、string、queue、map
开发语言·c++·算法
Bio Coder5 小时前
R语言安装生物信息数据库包
开发语言·数据库·r语言