Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to create right click menu of submenu?



  • I want a right click menu on submenu to delete QStringList item.
    alt text
    QStringList SL_bookmark_title,SL_bookmark_url;
    QMenu *submenu = new QMenu;
    for(int i=0;i<SL_bookmark_title.size();i++){
    QAction *action_bookmark_title = new QAction(submenu);
    action_bookmark_title->setText(SL_bookmark_title.at(i));
    action_bookmark_title->setToolTip(SL_bookmark_url.at(i));
    submenu->addAction(action_bookmark_title);
    connect(action_bookmark_title,SIGNAL(triggered(bool)),this,SLOT(gotoBookmarkURL(bool)));
    }
    action_bookmark->setMenu(submenu);



  • @sonichy hi,friend,welcome

    you can reimplemented void QWidget::contextMenuEvent(QContextMenuEvent *event) in a subclass to receive widget context menu events.

    Add submenu functions

    QAction *addMenu(QMenu *menu)
    QMenu *addMenu(const QString &title)
    QMenu *addMenu(const QIcon &icon, const QString &title)

    code snippet:

    void Widget::contextMenuEvent(QContextMenuEvent *event)
    {
        QMenu menu;
        menu.addAction(tr("act 1"));
        menu.addAction(tr("act 2"));
    
        /** add submenu */
        QMenu* subMenu = menu.addMenu(tr("sub menu"));
        subMenu->addAction("sub act1");
        subMenu->addAction("sub act1");
    
        QAction*  selAct = menu.exec(event->globalPos());
        if(0 != selAct){
             ///< do something....
        }
        QWidget::contextMenuEvent(event);
    }
    

  • Moderators

    @sonichy
    for the menu's main level you can create a custom QMenu sublass.
    Listen to the context menu event (as mentioned by @joeQ) in there and show a custom context-menu. Not sure if this works at all though.

    For the sub-menu level this is gonna be harder, since the sub-menu is created from the QAction and thus needs further implementations.


Log in to reply