有没有办法将QWidget添加到QtCreator中的QMenu

W.K*_*K.S 10 c++ qt qwidget qmenu

我创建一个文本编辑器,我想放QComboBox的QMenu.我没有在QMenu处理这样的事情中找到任何方法.最接近的是QMenu::addAction().我想知道绕过这个障碍.

谢谢!

pne*_*zis 17

你必须子类QWidgetAction,然后只需调用addAction你的菜单.

具有标签的Spin Box Action的示例代码

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;
};
Run Code Online (Sandbox Code Playgroud)

现在只需创建它并将其添加到菜单中

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);
Run Code Online (Sandbox Code Playgroud)

  • 这只是用`NULL`作为参数调用父的构造函数.http://stackoverflow.com/questions/120876/c-superclass-constructor-calling-rules (2认同)