Model / View框架:视图选择
2017-04-27 本文已影响0人
托尼章
概述
-
QItemSelectionModel:用来存储视图的选中项,或者基于同一个Model的多个视图的选中项。选择模型是独立于任何视图的,因为同一个模型可能对应多个视图,所以多个视图是可以共享同一个选择模型的。我们可以通过视图的selectionModel()函数可以获取到其对应的选择模型,通过视图的setSelectionModel()来重新设置其选择模型。
-
选择区域:选择模型是由多个选择区域组成的,每个选择区域记录了此区域的起始和结束模型索引;对于非常大的选择区域,只记录选择区域的开始和结束模型索引是非常高效的。同时拥有多个选择区域也可以方便的实现不连续的选择。
-
**Current Item 和 Selected Item **
Current Item | Selected Item |
---|---|
只能有一个当前项 | 可以同时有多个被选中项 |
当前项可以被鼠标或者按键导航改变 | 被选中项是通过set 或者unset来改变的,同时也要根据其他预设模式来决定--例如 单选,多选等。 |
按下F2或者双击鼠标左键当前项会被编辑(开启了编辑模式) | ** |
当前项由焦点矩形显示 | 选中项由选择矩形显示 |
示例
// 建立模型和视图
TableModel* model = new TableModel(8,4,&app);
QTableView* view = new QTableView(this);
view->setModel(model);
// 获取选择模型
QItemSelectionModel* selectionModel = view->selectionModel();
// 构造选择区域
QModelIndex topLeft = model->index(0,0,QModelIndex());
QModelIndex bottomRight = model->index(5,2,QModelIndex());
QItemSelection selection(topLeft,bottomRight);
// 选中项目
selectionModel->select(selection,QItemSelectionModel::Select);
以上代码的执行结果如下图: