10

Probably a trick question, but I can't find the answer.

I need to know when a QGraphicsItem gets selected. There must be a method that's called.

I know QGraphicsItem::itemChange() but it's called too often.

Is there a better method ?

thx

edit : With this

if(change == ItemSelectedChange && scene()){
    cout << "haha " << i++ << endl;
}

I get two calls every selection change.

Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134

2 Answers2

17

You should take value into consideration in the QGraphicsItem::itemChange method. What you want is probably something like this:

QVariant YourItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
    if (change == QGraphicsItem::ItemSelectedChange)
    {
        if (value == true)
        {
            // do stuff if selected
        }
        else
        {
            // do stuff if not selected
        }
    }

    return QGraphicsItem::itemChange(change, value);
}
Anthony
  • 8,570
  • 3
  • 38
  • 46
  • Thx Works better than what I found : add && this.isSelected() in the if. – Matthieu Riegler Apr 23 '12 at 21:14
  • @Anthony, I have a question on the else part. When I select another graphics item, the else part is getting triggered. I understand that. I am facing an issue that i need to get the else part triggered while on mouse press on another graphics item. Now it is triggering only when i press and release the mouse button on another graphics item. Is there any solution for this ? – GUI-Novice Mar 22 '18 at 12:11
  • @GUI-Novice I would try calling scene()->clearSelection() in the other item's mousePressEvent to ensure that this item gets deselected on a mouse press. – Anthony Mar 23 '18 at 03:28
0

QGraphicsScene::selectionChanged

ssc
  • 9,528
  • 10
  • 64
  • 94
Dave Mateer
  • 17,608
  • 15
  • 96
  • 149
  • You'd have to iterate over all [selected items](http://qt-project.org/doc/qt-5/qgraphicsscene.html#selectedItems]) and manually set the ones in question [selected](http://qt-project.org/doc/qt-5/qgraphicsitem.html#setSelected). – ssc Oct 14 '14 at 20:34