Derek
Derek

Reputation: 11905

How to run functions from context menu in QGraphicsItem

I am trying to implement a context menu in my QGraphicsItem subclass like so:

void ImagePixmapItem::right_clicked(){
    qDebug("Got here!");
}

void ImagePixmapItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event){
    QMenu menu;
    QAction *removeAction = menu.addAction("Remove");
    QAction *markAction = menu.addAction("Mark");
    QAction *selectedAction = menu.exec(event->screenPos());

    connect(selectedAction, SIGNAL(triggered()),this, SLOT(right_clicked()));
}

What am I doing wrong? The text "Got here!" never gets fired, and further, how do I modify this to know which action was selected from the menu?

Thanks

Upvotes: 1

Views: 1761

Answers (1)

Naszta
Naszta

Reputation: 7744

The QMenu is deleted when the menu object goes out of scope.

Try this:

void ImagePixmapItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
    std::auto_ptr<QMenu> menu(new QMenu(address_of_parent_widget));
    QAction *removeAction = menu->addAction("Remove");
    QAction *markAction = menu->addAction("Mark");
    QAction *selectedAction = menu->exec(event->screenPos());
    if ( selectedAction != 0 ) { 
        // see: http://doc.trolltech.com/4.3/qmenu.html#exec-2
        this->right_clicked();
    }
}

Upvotes: 1

Related Questions