基本上,我们遇见的各种软件,最上方都有一行菜单栏,菜单栏实现了各种功能,Qt的QMainWindow控件提供了MenuBar,可在MenuBar上方便的添加菜单,但是有时候我们并不需要很多的菜单,有一个就够了,这个时候如果还使用MenuBar,那么在界面显示上会显得不是那么美观。因此我们会找更好的方法进行菜单的设置,使用QPushButton和菜单结合起来使用就能够很方便的完成这种需求。
1、常规模式
QPushButton累提供了setMenu方法,如下:
void QPushButton::setMenu(QMenu *menu)
Associates the popup menu menu with this push button. This turns the button into a menu button, which in some styles will produce a small triangle to the right of the button's text.
Ownership of the menu is not transferred to the push button.
大概意思就是,将弹出式菜单与此按钮关联,普通按钮转换成菜单按钮,在某些样式中按钮的右侧会显示一下倒三角,但是菜单的属性并没有转移到按钮。
以上,我们就能很快的生成自己的按钮。
QPushButton* pBtn = new QPushButton();
QMenu* pMenu = new QMenu(this);
pBtn->setMenu(pMenu);
QAction* pAction = new QAction(this);
pMenu->addAction(pAction);
pAction->setText(tr("save as ..."));
connect(pAction, SIGNAL(triggered()), this, SLOT(slot_menuClicked()));
以上,我们就已经生成了菜单按钮,如果我们不想要右侧的下拉三角,则可以通过qss的方式隐藏。QPushButton::menu-indicator{ image:none;}
2、非常规模式
对于初学Qt者,可能不知道上面常规模式的方法,所以在实现过程中会遇到一些麻烦,因此建议:Qt有很强大的文档说明,强烈建议使用Qt是经常性的查一查文档,把文档当作字典也是好的。
所以我们使用QPushButton和QWidget也能够实现上面的菜单,只是在处理上会比较麻烦一点。
auto* pBtn = new QPushButton();
auto* pWidget = new QWidget(this);
auto* layout = new QVBoxLayout;
auto* pAction1 = new QPushButton(tr("save"), this);
auto* pAction2 = new QPushButton(tr("save as ..."), this);
layout->setSpacing(10);
layout->setMargin(0);
layout->addWidget(pAction1);
layout->addWidget(pAction2);
pWidget->setLayout(layout);
connect(pAction1, &QPushNutton::clicked, this, &XXX::slot_menuClicked);
connect(pAction2, &QPushNutton::clicked, this, &XXX::slot_menuClicked);
void XXX::slot_menuClicked()
{
auto btn = qobject_cast<QPushButton*>(sender());
QString strMenu = btn->text();
}
由上,通过获取信号的发送者我们就能够知道是哪个按钮被点击了,也就能够正确的执行后续的操作,当然,给菜单的每个按钮关联不同的槽函数,就不必这么麻烦了。这种方法实现起来也是比较简单的, **缺点就是:**每次pWidget的显示和隐藏需要手动调用,因此相比较常规模式,不是很灵活。