3

I am new to Qt. It seems the default for multiple selection of qgraphicsitem is to press ctrl button. But is it possible to disable this function? Or reload this function?

2 Answers 2

4

This is controlled by the items' flags. To disable selection for a particular item, do

item->setFlag(QGraphicsItem::ItemIsSelectable, false);

If you want to completly disable selecting items for a QGraphicsScene regardless of the item flags I would recommend to connect QGraphicsScene::selectionChanged to QGraphicsScene::clearSelection.

If you want to disable multiple selection I suggest the following:

  • Subclass QGraphicsScene and keep a pointer lastSelection to a QGraphicsItem around
  • Create a slot connected to QGraphicsScene::selectionChanged
  • Check selectedItems:
    • it's empty: nothing to do (=nothing selected)
    • contains only lastSelection: nothing to do (=selection didn't really change)
    • contains one item, not lastSelection: set lastSelection to that item (=one item selected for the first time)
    • contains two items: One must be lastSelection. Remove that one from the selection (lastSelection->setSelected(false);), set lastSelection to the remaining item. (=another item was selected, move selection to it)

You might need to block signals during modifying the selection inside the slot.

4
  • Hi, but I still want to keep normal selection ability, I only want to disable the multiple selection...
    – Nyaruko
    Oct 7, 2014 at 6:21
  • Sorry, but what's the purpose of blocking signals during modifying the selection inside a slot?
    – Nyaruko
    Oct 8, 2014 at 8:38
  • I'm not sure who handles the selection behind the scenes. If the items do it, it might be possible to create a signal loop when modifying the selection from a selectionChanged slot. Thus it might be necessary to block signals.
    – dom0
    Oct 8, 2014 at 10:16
  • @dom0 +1 but there is no need to block signals if you do the checks in the order that you described
    – Oliver
    Feb 24, 2016 at 2:39
3

The simple way to disable multiple selection is:

  1. Create your own Dirived class from QGraphicsItem.
  2. Overload the protected mousePressEvent function and disable ControlModifier:

    protected:
        void YourOwnQGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent) Q_DECL_OVERRIDE
        {
            if(mouseEvent->modifiers() & Qt::ControlModifier)
            {
                mouseEvent->ignore();
            }
            else
            {
                QGraphicsItem::mousePressEvent(mouseEvent);
                //Do what you want...
            }
        }
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.