Nyaruko
Nyaruko

Reputation: 4459

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?

Upvotes: 3

Views: 3605

Answers (3)

Hisham
Hisham

Reputation: 103

Here’s an alternate approach that does not require derivation. It deselects all the objects in a scene except the one you want selected:

template <class ObjectT>
void SelectObjectUniquely ( ObjectT & rObject, QGraphicsScene & rScene )
{
    rObject.setSelected ( true );

    QList<QGraphicsItem *>  graphic_items = rScene.selectedItems();

    for ( auto it : graphic_items )
    {
        QGraphicsItem * the_item = it;

        if ( it != &rObject )
            it->setSelected ( false );
    }
}

ObjectT is an object derived from QGraphicsItem.

Upvotes: 0

Timur  Mamedov
Timur Mamedov

Reputation: 31

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

Upvotes: 3

dom0
dom0

Reputation: 7486

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.

Upvotes: 3

Related Questions