Qt World Summit: Submit your Presentation

QContextMenu over which widget?

  • Is there a way to determine what widget is under the context menu? I want to adjust my context menu based on what widget is at the context position.

    I have tried variations of childAt but have not had any luck. For example if I am wondering if I am over a specific QTreeView I have tried things like:

    void SomeClass::contextMenuEvent(QContextMenuEvent * event)
    QWidget * p = static_cast<QWidget*>(_treeView->parent());
    QTreeView * tv = dynamic_cast<QTreeView*>( p->childAt( p->mapFromGlobal(event->globalPos()) ) );
    if( tv==_treeView ) // add items x,y & z to my context menu

    However "tv" is always NULL even if I trigger the context menu in the middle of my QTreeView.

    Any ideas? Thanks.

  • As far as I know there is QWidget::contextMenuEvent virtual method. This way you can show context menu directly from your widget, without any additional recognition. You could for example inherit QTreeView and just implement contextMenuEvent to show customized context menu just for this particular widget.

  • That is true however I have some global menu items for that entire window but only want to show certain options when I am over certain widgets.

  • set "contextMenuPolicy":http://developer.qt.nokia.com/doc/qt-4.7/qwidget.html#id-36e9c206-1ce6-47bd-b618-dacdfbbcf7b6

    Then, u can trigger the custom Context Menu request by

    @connect(QWidget,SIGNAL(customContextMenuRequested ( const QPoint & pos )),this,SLOT(showYourMenu(const QPoint & pos)));@

    Cheers.. :)

  • Perfect, thanks!!

Log in to reply