问题
How do I add a submenu from the menu below? I need a submenu to open, say, after clicking
"A->Setup"
I want a submenu to be opened to the side of the main menu.
void MyMenu::cppSlot()
{
QMenu *xmenu = new QMenu;
xmenu->addMenu("A -> Setup");
xmenu->addMenu("B -> Setup");
xmenu->addMenu("C -> Setup");
xmenu->addMenu("D -> Setup");
xmenu->addMenu("E -> Setup");
//Change font and width
xmenu->setFont(QFont ("Courier", 10));
xmenu->setFixedWidth(250);
//Colour setting
xmenu->setAutoFillBackground(true);
/*QPalette palette=xmenu->palette();
palette.setColor(QPalette::Window, Qt::black);
palette.setColor(QPalette::Window, Qt::text);
palette.color(green)
xmenu->setPalette(palette);*/
// Align the menu coordinates
// xmenu->
xmenu->move(900,300);
xmenu->show();
}
回答1:
QMenu::addMenu() returns a pointer to the created submenu. You can use these pointers to add actions for the submenus.
The following code:
QMenu *xmenu = new QMenu();
QMenu* submenuA = xmenu->addMenu( "A" );
QMenu* submenuB = xmenu->addMenu( "B" );
QMenu* submenuC = xmenu->addMenu( "C" );
QMenu* submenuD = xmenu->addMenu( "D" );
QMenu* submenuE = xmenu->addMenu( "E" );
QAction* actionA_Setup = submenuA->addAction( "Setup" );
QAction* actionB_Setup = submenuB->addAction( "Setup" );
QAction* actionC_Setup = submenuC->addAction( "Setup" );
QAction* actionD_Setup = submenuD->addAction( "Setup" );
QAction* actionE_Setup = submenuE->addAction( "Setup" );
(Hint: This cries for a loop)
will produce a menu like this:
You can then connect slots to the triggered()
signal of the returned actions (e.g. actionA_Setup
).
来源:https://stackoverflow.com/questions/13799033/how-to-add-submenu-in-qt