如何在Qt中添加子菜单

时间:2012-12-10 10:25:16

标签: qt qt4 qt-creator

如何从下面的菜单中添加子菜单?点击

后,我需要打开一个子菜单
"A->Setup"

我希望在主菜单旁边打开一个子菜单。

   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 个答案:

答案 0 :(得分:21)

QMenu::addMenu()返回指向已创建子菜单的指针。您可以使用这些指针为子菜单添加操作。

以下代码:

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" );

(提示:这需要一个循环)

将生成如下菜单:

Screenshot of the created menu

然后,您可以将广告连接到返回操作的triggered()信号(例如actionA_Setup)。