1

我试图在我的 QGraphicsItem 子类中实现一个上下文菜单,如下所示:

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()));
}

我究竟做错了什么?文字“到了!” 永远不会被解雇,此外,我如何修改它以知道从菜单中选择了哪个操作?

谢谢

4

1 回答 1

1

当菜单对象超出范围时,QMenu 将被删除。

试试这个:

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();
    }
}
于 2011-04-07T20:28:49.453 回答