How to dynamically add menus in Qt

I want to add a submenu to a menu item dynamically. How can I achieve this?

I tried like this, I created an Action and a submenu. Then I added a submenu to the action. But I connected the "triggered" action signal. its getting an accident if i click on the action ..

I also handled the "aboutToShow" menu signal, just like when it crashed when I clicked on an action.

Here is the sampe code.

Submenu = new QMenu(this);      
connect(Submenu, SIGNAL( aboutToShow()), this, SLOT(move ()));

                  QAction *test = new QAction(tr("Selection"), this);
                  test ->setMenu(Submenu);

                 menubar()->addAction(test);

I want to be notified before submitting a submenu.

Additional Information:

try this code in the main window constructor.

QAction *action = new QAction("Test",this);
QAction *dummyaction = new QAction("Testing",this);
QMenu *menu = new QMenu();
menu->addAction(dummyaction);

bool val= connect(menu, SIGNAL( aboutToShow()), this, SLOT( Move()));
val= connect(menu, SIGNAL( aboutToHide()), this, SLOT(Move()));

action->setMenu(menu);
this->menuBar()->addAction(action);

if I like it, I can see one element of the submenu. But before that, the Move slot should call, it will not be called .. and even before the hide, the same slot should also call .. it won’t come ..

connect.. ... .. , .

+3
2

, , Move().

( , ), , :

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

#include <QAction>
#include <QMenu>

class MainWindow : public QMainWindow
{
   Q_OBJECT

public:
   explicit MainWindow(QWidget *parent = 0);

private:
   QMenu* menu;
   QAction *dummyaction;
   QMenu* m_pSubMenu;
 private slots:
    void Move();
};

#endif // MAINWINDOW_H

mainwindow.cpp:

#include "mainwindow.h"

#include <QMenuBar>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
   m_pSubMenu = NULL;
   QMenuBar* pMenuBar = new QMenuBar(this);

   setMenuBar(pMenuBar);

   dummyaction = new QAction("Testing",this);
   menu = new QMenu("Test", this);
   menu->addAction(dummyaction);
   this->menuBar()->addMenu(menu);

   connect(menu, SIGNAL(aboutToShow()), this, SLOT(Move()));
}

void MainWindow::Move() {
   if (!m_pSubMenu) {
      m_pSubMenu = new QMenu(menu);
      dummyaction->setMenu(m_pSubMenu);
   }
   QAction* pAction = new QAction("Test", this);
   m_pSubMenu->addAction(pAction);
}

, Move(), , , , Move(), .

, .

+2

:

QMainWindow wnd;
QAction *act = wnd.menuBar()->addMenu("SomeMenu")->addMenu("someSubmenu")->addAction("someAction");
QObject::connect(act,SIGNAL(triggered()),
                 someObj,SLOT(actionReaction()));

, addMenu() addAction() . .

+1

Source: https://habr.com/ru/post/1744331/


All Articles