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!
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!
You have to subclass QWidgetAction
and then simply call the addAction
to your menu.
Example code for Spin Box Action with a label
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;
};
Now simply create it and add it to your menu
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
I was able to have a reusable element, and in every case I only had to change the constructor arguments. Also it is straight forward to create a small library with action widgets and just call the one you need when you need it. –
Vair SpinBoxAction (const QString& title) : QWidgetAction (NULL) {}
–
Calendar NULL
as argument. #121376 –
Vair QWidgetAction
is a QAction
that contains a QWidget
. You can use this to encapsulate your QComboBox
and add it to your menu via QMenu::addAction
.
You can always use a QWidget
or QFrame
as the Menu Widget, then put a QHBoxLayout
on it, and insert your QWidgets
inside.
© 2022 - 2024 — McMap. All rights reserved.
pWidget
and callsetDefaultWidget
? Wouldn't the only reason to subclass be to implementcreateWidget
? – Nix