how to add menu dynamically in Qt

Naruto picture Naruto · May 6, 2010 · Viewed 16.6k times · Source

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

I tried like this, I have created an Action and submenu. Then I have added the submenu to action. But, I have connected the “triggered” signal of action. its getting crash if I click on the action..

I have also handled the “aboutToShow” signal of menu, same its also getting crash when I click on 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 get the notification, before the display of submenu..

additonal information:

pleas try this code, in your 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 do like this, I am able to see one submenu item. But before that Move slot should call, its not getting called.. and even before hide also the same slot should call.. its not coming..

I tried the return values of connect.. its true only… so what is wrong with my code.. please say..

Answer

VestniK picture VestniK · May 6, 2010

Such code should work:

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

I think addMenu() addAction() should work in more reliable way. This approach works for me.