Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to add a QWidget to a QMenu in QtCreator

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!

like image 940
W.K.S Avatar asked Dec 02 '11 15:12

W.K.S


3 Answers

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);
like image 181
pnezis Avatar answered Sep 18 '22 23:09

pnezis


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.

like image 25
Magnus Hoff Avatar answered Sep 19 '22 23:09

Magnus Hoff


You can always use a QWidget or QFrame as the Menu Widget, then put a QHBoxLayout on it, and insert your QWidgets inside.

like image 30
Tomaz Canabrava Avatar answered Sep 16 '22 23:09

Tomaz Canabrava