11

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!

4

3 回答 3

19

您必须进行子类QWidgetAction化,然后只需调用addAction您的菜单。

带有标签的旋转框操作的示例代码

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

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

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);
于 2011-12-02T16:23:08.557 回答
2

QWidgetActionQAction包含 a 的 a QWidget。您可以使用它来封装您的QComboBox并将其添加到您的菜单中QMenu::addAction

于 2011-12-02T16:23:33.177 回答
1

您始终可以使用 aQWidgetQFrame作为 Menu Widget,然后将 aQHBoxLayout放在上面,然后插入您的QWidgets内部。

于 2011-12-02T16:12:26.223 回答