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

淺唱寂寞╮ 提交于 2019-12-09 09:58:33

问题


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!


回答1:


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);



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/8358965/is-there-a-way-to-add-a-qwidget-to-a-qmenu-in-qtcreator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!