Search code examples
c++qtqgraphicsitem

How to disable the multiple selection of qgraphicsitem?


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?


Solution

  • 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.