I'm creating a text editor and I'd like to put the QComboBox
in the QMenu
. I didn't find any method inside the QMenu
that handled such a thing. The closest is QMenu::addAction()
. I was wondering of getting around this hurdle.
Thanks!
您必须进行子类QWidgetAction
化,然后只需调用addAction
您的菜单。
带有标签的旋转框操作的示例代码
class SpinBoxAction : public QWidgetAction {
public:
SpinBoxAction (const QString& title) :
QWidgetAction (NULL) {
QWidget* pWidget = new QWidget (NULL);
QHBoxLayout* pLayout = new QHBoxLayout();
QLabel* pLabel = new QLabel (title); //bug fixed here, pointer was missing
pLayout->addWidget (pLabel);
pSpinBox = new QSpinBox(NULL);
pLayout->addWidget (pSpinBox);
pWidget->setLayout (pLayout);
setDefaultWidget(pWidget);
}
QSpinBox * spinBox () {
return pSpinBox;
}
private:
QSpinBox * pSpinBox;
};
现在只需创建它并将其添加到您的菜单中
SpinBoxAction * spinBoxAction = new SpinBoxAction(tr("Action Title"));
// make a connection
connect(spinBoxAction ->spinBox(), SIGNAL(valueChanged(int)),
this, SLOT(spinboxValueChanged(int)));
// add it to your menu
menu->addAction(spinBoxAction);
QWidgetAction
是QAction
包含 a 的 a QWidget
。您可以使用它来封装您的QComboBox
并将其添加到您的菜单中QMenu::addAction
。
您始终可以使用 aQWidget
或QFrame
作为 Menu Widget,然后将 aQHBoxLayout
放在上面,然后插入您的QWidgets
内部。