PDA

View Full Version : QGraphicsItem deselected on contextMenuEvent



D Cell
14th December 2010, 05:25
Hi,

I have subclassed QGraphicsScene and want to reimplement the QGraphicsScene::contextMenuEvent(QGraphicsSceneCon textMenuEvent *) function. My plan was to catch all context events with the scene and dynamically create a context menu depending on the combination of types of QGraphicsItems selected. I want the menu to only contain actions that all selected items will support. I started like this:



void MyScene::contextMenuEvent(QGraphicsSceneContextMen uEvent *contextMenuEvent)
{
QList<QGraphicsItem *> selected = selectedItems(); // Always returns an empty list
// Create context menu dynamically here and execute it
}

The problem I am encountering is that a right click context menu event deselects all items in the scene. This bug is documented here (http://bugreports.qt.nokia.com/browse/QTBUG-10138). I need some sort of workaround, but am struggling with this one. Anyone have any ideas? Thanks in advance.

Hmmm...I found a solution. The Qt docs for QGraphicsScene::mousePressEvent(...) state:

If there is no item at the given position on the scene, the selection area is reset, any focus item loses its input focus, and the event is then ignored.

I had reimplemented this function, but wasn't accepting anything but left mouse button events. Accepting right click mouse button events solved the problem:



void MyScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if (event->button() != Qt::LeftButton) {
event->accept();
return;
}
QGraphicsScene::mousePressEvent(event);
}