How to add submenu in Qt

空扰寡人 提交于 2021-02-04 14:30:14

问题


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:

Screenshot of the created menu

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!