自定义一个窗口部件的时候,并不会像QmainWindow那样自带菜单部件,此时需要给他添加一个菜单,如下:
void BoxFrame::createMenu()
{
//自定义部件
QWidget *wd = new QWidget;
QPushButton *btn = new QPushButton("按键");
QHBoxLayout *layout = new QHBoxLayout(wd);
layout->addWidget(btn);
wd->setLayout(layout);
wd->setStyleSheet("background-color:rgb(0,200,0)");
QWidgetAction *pWdtAction = new QWidgetAction(this);
pWdtAction->setDefaultWidget(wd);
//新建二级菜单
QMenu *pMenuNew = new QMenu(QString("新建"));
pMenuNew->addAction(QString("测试1"));
pMenuNew->addAction(QString("测试2"));
pMenuNew->addAction(QString("测试3"));
pMenuNew->addAction(QString("测试4"));
pMenuNew->addAction(QString("测试5"));
//生成菜单栏
QMenu *pMenu = new QMenu(this);
pMenu->addAction(pWdtAction);
pMenu->addSeparator();
//pMenu->addAction(QString("新建"));
pMenu->addMenu(pMenuNew);
pMenu->addAction(QString("打开"));
pMenu->addSeparator();
pMenu->addAction(QString("保存"));
pMenu->addAction(QString("另存"));
pMenu->addSeparator();
pMenu->addAction(QString("打印"));
pMenu->addAction(QString("退出"));
ui->btnCfg->setMenu(pMenu);
//ui->btnCfg->setStyleSheet("QPushButton::menu-indicator{image:None;}"); //去除右边小三角
}
效果图: