将自定义小部件添加到QMenuBar [英] Adding custom widgets to QMenuBar

查看:383
本文介绍了将自定义小部件添加到QMenuBar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Qt3用于为QMenuBar :: insertItem提供QWidget *参数.这样,可以将任何自定义窗口小部件添加到菜单栏,例如Clock-widget. 在Qt4中,没有这样的重载方法.达到相同目标的最佳方法是什么-向菜单栏添加自定义窗口小部件?自定义窗口小部件应集成在菜单栏的布局中. 是否知道背景,为什么在Qt4 API中删除了insertItem的这种重载?

Qt3 used to provide QMenuBar::insertItem with QWidget* parameter. This way any custom widget could be added to menu bar - for example a clock-widget. In Qt4 there is no such overloaded method. What would be the best way to reach the same goal - adding custom widgets to a menu bar? The custom widgets should be integrated in the layout of menu bar. Does anyoune knows the background, why this overload of insertItem was removed in Qt4 API?

最诚挚的问候.

推荐答案

抱歉,哈维尔(Javier)的简短评论.每当我想换行时,都会提交评论:-(

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

我在使用QtCreator创建的项目中尝试了以下代码:

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
}

仅添加QAction(1)起作用.没有使用默认小部件添加QWidgetAction而不将QWidgetAction子类化都没有得到结果.我已经在C-Tor和MyWidgetAction的两个虚拟函数中设置了断点.令人惊讶的是,仅击中了C-Tor断点. 我已经在Windows上使用Qt4.6.3的MinGW开源版本尝试过 这可能是Qt中的错误吗? 非常感谢您的任何建议!

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!

关于, 瓦伦丁·海尼兹(Valentin Heinitz)

Regards, Valentin Heinitz

这篇关于将自定义小部件添加到QMenuBar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆