天天看点

QGraphicsItem分组简述分组方式QGraphicsItemGroup示例

qgraphicsitem 支持很多特性,例如:鼠标、键盘事件、拖放、分组、碰撞检测等。

通常在演示工具中使用分组,当用户想要将多个较小的 items 组合成一个大的 item 时,以简化 items 的移动和复制。

<a href="#%e7%ae%80%e8%bf%b0">简述</a>

<a href="#%e5%88%86%e7%bb%84%e6%96%b9%e5%bc%8f">分组方式</a>

<a href="#qgraphicsitemgroup">qgraphicsitemgroup</a>

<a href="#%e7%a4%ba%e4%be%8b">示例</a>

<a href="#%e6%95%88%e6%9e%9c">效果</a>

<a href="#%e6%ba%90%e7%a0%81">源码</a>

分组方式有两种:

通过父子关系 - 如果想要将 items 存储在其他 item 内,可以直接将任何 qgraphicsitem 通过为 setparentitem() 传递一个合适的 parent。

qgraphicsitemgroup - 提供了一个容器,将一组 items 视为单个 item。

注意: 对于方式一,qgraphicsitem 可以有自己的子 item 对象。但是,qgraphicsitem 没有 api(例如:setitems()、addchild())添加孩子,它只能允许孩子附加到 parent (setparentitem()),想想也挺神奇的。

qgraphicsitemgroup 是一种特殊类型的复合 item,将自身及其所有子项视为一个 item(即,其所有子项的所有事件和几何图形都被合并在一起)。

qgraphicsitemgroup 的 boundingrect() 函数返回位于其中所有 items 的边界矩形。qgraphicsitemgroup 忽略其子项上的 itemignorestransformations 标记(即,相对于 qgraphicsitemgroup 的 geometry,子项被视为可变换的)。

要构造一个 qgraphicsitemgroup,有两种方式:

将一个 items 列表(例如:所有选择的 items)传递给 qgraphicsscene::createitemgroup(),它返回一个新的 qgraphicsitemgroup(最简单、最常见的方式)。

手动构造一个 qgraphicsitemgroup,使用 qgraphicsscene::additem() 将其添加到场景中,然后通过调用 addtogroup() 为 group 手动添加 item,一次只能添加一个。

要拆卸(取消组合)一个 qgraphicsitemgroup,可以调用 qgraphicsscene::destroyitemgroup(),也可以通过调用 removefromgroup() 从 group 中手动删除所有 items。

常用的软件,例如:xmind、visio 都有分组功能。下面,我们实现一个简单的分组,利用一个直线(链接线)将椭圆和矩形连接起来。

QGraphicsItem分组简述分组方式QGraphicsItemGroup示例