Is there a way to add QWidget to QMenu in QtCreator

I am creating a text editor and I would like to put the QComboBox in QMenu . I did not find any method inside QMenu that handled such a thing. The closest is QMenu::addAction() . I was interested in getting around this obstacle.

Thanks!

+10
c ++ qt qwidget qmenu
source share
3 answers

You have to QWidgetAction subclass of QWidgetAction and then just call addAction in your menu.

Sample code for Spin Box Action with 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 just 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); 
+17
source share

You can always use a QWidget or QFrame as a menu widget, then put a QHBoxLayout on it and paste your QWidgets inside.

+1
source share

QWidgetAction is a QAction containing a QWidget . You can use this to encapsulate your QComboBox and add it to your menu through QMenu::addAction .

+1
source share

All Articles