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 都有分組功能。下面,我們實作一個簡單的分組,利用一個直線(連結線)将橢圓和矩形連接配接起來。