Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You want to change the default behavior of <code>QGraphicsScene</code>, so you have to create your own scene class, inheriting <code>QGraphicsScene</code>.</p> <p>In your class, you'll have to reimplement at least <code>mousePressEvent</code> and handle the item selection yourself.</p> <p>Here is how you could do it (the inherited scene class is called <code>GraphicsSelectionScene</code>) :</p> <pre><code>void GraphicsSelectionScene::mousePressEvent(QGraphicsSceneMouseEvent* pMouseEvent) { QGraphicsItem* pItemUnderMouse = itemAt(pMouseEvent-&gt;scenePos().x(), pMouseEvent-&gt;scenePos().y()); if (!pItemUnderMouse) return; if (pItemUnderMouse-&gt;isEnabled() &amp;&amp; pItemUnderMouse-&gt;flags() &amp; QGraphicsItem::ItemIsSelectable) pItemUnderMouse-&gt;setSelected(!pItemUnderMouse-&gt;isSelected()); } </code></pre> <p>Implementing this way, clicking on an item with select it if it is not already, or will unselect it otherwise.</p> <p>But be careful, implement <code>mousePressEvent</code> is certainly not enough : you'll have to handle the <code>mouseDoubleClickEvent</code>as well if you don't want the default behavior.</p> <p>Your scene will have to be displayed by a <code>QGraphicsView</code>. Here is an example of a view creating it's own scene (<code>MainFrm</code> class is inheriting <code>QGraphicsView</code>) :</p> <pre><code>#include "mainfrm.h" #include "ui_mainfrm.h" #include "graphicsselectionscene.h" #include &lt;QGraphicsItem&gt; MainFrm::MainFrm(QWidget *parent) : QGraphicsView(parent), ui(new Ui::MainFrm) { ui-&gt;setupUi(this); // Create a scene with our own selection behavior QGraphicsScene* pScene = new GraphicsSelectionScene(this); this-&gt;setScene(pScene); // Create a few items for testing QGraphicsItem* pRect1 = pScene-&gt;addRect(10,10,50,50, QColor(Qt::red), QBrush(Qt::blue)); QGraphicsItem* pRect2 = pScene-&gt;addRect(100,-10,50,50); QGraphicsItem* pRect3 = pScene-&gt;addRect(-200,-30,50,50); // Make sure the items are selectable pRect1-&gt;setFlag(QGraphicsItem::ItemIsSelectable, true); pRect2-&gt;setFlag(QGraphicsItem::ItemIsSelectable, true); pRect3-&gt;setFlag(QGraphicsItem::ItemIsSelectable, true); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload