Adding slots to automatically created menu items

Gandalf picture Gandalf · Sep 2, 2011 · Viewed 8.6k times · Source

I have an existing menu called save and in it i want to add two menus,Save New and Save Edits.

QMenu *menu = new QMenu(this);
menu->addAction("Save New");//void saveNew()
menu->addAction("Save Edits");//void saveEdits()
ui.saveButton->setMenu(menu);

I have looked up for a suitable function and found this but i need help implemening it.

QAction * QMenu::addAction ( const QString & text, const QObject * receiver, const char * member, const QKeySequence & shortcut = 0 )

How can i do it?.

Answer

alexisdm picture alexisdm · Sep 2, 2011
menu->addAction("Save New", this, SLOT(saveNew()));

With the same parameters you would use in that connect call:

QAction *saveAction = menu->addAction("Save New");
connect(saveAction, SIGNAL(triggered()), this, SLOT(saveNew()));

If the menu was created in the designer, you can connect the corresponding actions that were created at the same time:

connect(ui.saveAction, SIGNAL(triggered()), this, SLOT(saveNew()));

or use the signal/slot editor to connect directly the actions from within the designer.