【问题标题】:Is there a way to add a QWidget to a QMenu in QtCreator有没有办法在 QtCreator 中将 QWidget 添加到 QMenu
【发布时间】:2012-01-11 15:18:49
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: c++ qt qwidget qmenu


    【解决方案1】:

    您必须继承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;
    };
    

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

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

    【讨论】:

    • 为什么更喜欢继承 QWidgetAction?它不会提供更松散的耦合和更可维护的代码来实例化 QWidgetAction 与您的pWidget 分开并调用setDefaultWidget 吗?子类化的唯一原因难道不是实现createWidget吗?
    • 视情况而定。如果您想拥有可重用的小部件操作并避免重写代码的相同部分来创建它们,您应该将它们子类化。例如,我曾经需要一个带有多个带有标签的旋转框的 QMenu,以及不同的最小/最大值和前缀。通过继承QWidgetAction,我能够拥有一个可重用的元素,并且在每种情况下我只需要更改构造函数参数。此外,还可以直接创建一个带有操作小部件的小型库,并在需要时调用您需要的小部件。
    • 我不熟悉这种构造函数:SpinBoxAction (const QString& title) : QWidgetAction (NULL) {}
    • 这只是以NULL 作为参数调用父级的构造函数。 stackoverflow.com/questions/120876/…
    • @MagnusHoff 那么为什么需要实现 createWidget?
    【解决方案2】:

    QWidgetAction 是一个包含QWidgetQAction。您可以使用它来封装您的QComboBox,并通过QMenu::addAction 将其添加到您的菜单中。

    【讨论】:

      【解决方案3】:

      您始终可以使用QWidgetQFrame 作为菜单小部件,然后在其上放置QHBoxLayout,并在其中插入您的QWidgets

      【讨论】:

      • 这个想法其实是我想到的。我对 Qt 有点陌生,所以如果这有点基本,请原谅我:如何将我自己的 QWidget 设置为菜单小部件。
      猜你喜欢
      • 2018-11-30
      • 2011-11-22
      • 2016-12-13
      • 2022-01-13
      • 2017-09-24
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 2020-03-26
      相关资源
      最近更新 更多