Adding custom widgets to QMenuBar

筅森魡賤 提交于 2019-12-05 12:30:25

there's a QMenuBar::addAction ( QAction * action ) method, to add an arbitrary QAction to the menu bar.
For example, it could be a QWidgetAction, which is a subclass of QAction with an associated QWidget instead of just an icon + text.

Sorry Javier for short comments. Every time I intended to break a line, the comment was submitted :-(

I tried this code in a project created with QtCreator:

class MyWidgetAction : public QWidgetAction
{
public:
    MyWidgetAction( QObject * parent ) :QWidgetAction (  parent )
    {

    }
    void releaseWidget ( QWidget * widget )
    {
        widget->deleteLater();
    }

    QWidget * requestWidget ( QWidget * parent )
    {
        QPushButton *b = new QPushButton( tr("MyWidget"), parent );
        b->show();
        return b;
    }
};

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);    
    QAction *a = new QAction(tr("TestAction"),this); //1
    QWidgetAction * wa = new QWidgetAction(this);    //2
    wa->setDefaultWidget(new QPushButton("Default"));
    MyWidgetAction *mwa = new MyWidgetAction(this);  //3

    ui->menuBar->addAction( a ); //1 - works. TestAction added to menu bar
    ui->menuBar->addAction( wa ); //2 - noop. nothing added to menu bar
    ui->menuBar->addAction( mwa ); //3 - noop. nothing added to menu bar
}

Only adding QAction (1) worked. Neither adding QWidgetAction with default widget not subclassing QWidgetAction gave a result. I've set breakpoints in C-Tor and both virtual functions of MyWidgetAction. Surprisingly, only C-Tor break-point was hit. I've tried on Windows with Open-Source, MinGW version of Qt4.6.3 Could it be a bug in Qt? Thank you very much in advance for any suggestions!

Regards, Valentin Heinitz

I was only able to do this by adding my QMenuBar and custom widget to a new QWidget and using THAT as the menubar:

MenuWidget::MenuWidget(QWidget *parent, Qt::WFlags flags)
    : QMainWindow(parent, flags)
{
    ui.setupUi(this);

    QWidget *w = new QWidget(this);
    QHBoxLayout *layout = new QHBoxLayout(w);

    layout->addWidget(ui.menuBar);

    QLineEdit *edit = new QLineEdit("", w);
    layout->addWidget(edit);

    layout->addStretch(10);

    setMenuWidget(w);
}

This works for Windows, but it doesn't work on the Mac.

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