Add a context menu to a dialog using QTCreator



  • Hi All,
    hope someone can help me out. I want to add a right click menu ( think this is a context menu ?) to my software using QT creator, but am having trouble find out about this. What I've done in creator is click on dialog and added a slot for "customcontextmenurequest" this produces a function

    void Game_View_Dialog::on_treeView_customContextMenuRequested(const QPoint &pos)
    

    however right clicking on the dialog did nothing. After some searching and experimentation I've found if I go to the treeview properties and change "contextmenupolicy" to "customcontextmenu" right clicking now drops into the on_treeView_customContextMenuRequested function.
    But now I need to find how to draw the menu, fill it with text (open,edit ect ) and call a function when I select the name (eg edit ).
    Can anyone advise how I'd do this from where I'm at?

    Thanks


  • Moderators

    See here: http://doc.qt.io/qt-5/qtwidgets-mainwindows-menus-example.html
    At the bottom you find an example for context menu.



  • Thanks but I really can't figure out how I get from slot to call a custom menu

    void Game_View_Dialog::on_treeView_customContextMenuRequested(const QPoint &pos)
    

    to using QMenu menu( this ); when this is a QWidget and this in my class is a qDialog? I just get an error because of this? Are there any tutorials using QT creator to show how to create a context menu, I don't seem to be be able to find any, or I'm fundamentally misunderstanding it


  • Moderators

    Since QDialog is a QWidget you can reimplement

    contextMenuEvent(QContextMenuEvent * event)
    

    It is described in the documentation, I sent you the link before:

    void YourDialog::contextMenuEvent(QContextMenuEvent *event)
    {
        QMenu menu(this);
        menu.addAction(cutAct);
        menu.addAction(copyAct);
        menu.addAction(pasteAct);
        menu.exec(event->globalPos());
    }
    

    See here how to add QAction to your menu: http://doc.qt.io/qt-5/qaction.html


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.