Calvin Froedge
Calvin Froedge

Reputation: 16373

Global menu in Qt with QtMenuBar

I'm new to C++ and Qt, and I'm having a bit of trouble getting off the ground. I'd really appreciate some help. I want to add a menubar that will remain constant for all app screens. If I add this to the main function, the menubar shows up fine, but I know this shouldn't be in my main function:

#include <QtGui/QApplication>
#include "mainwindow.h"
#include "form.h"
#include "menu.h"


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;

    QMenuBar *menu = new QMenuBar(0);
    QMenu* menu1 = new QMenu("MENU1");
    menu1->addMenu(new QMenu("menu1_SubMenu"));

    QMenu* menu2 = new QMenu("MENU2");
    menu2->addMenu(new QMenu("menu2_SubMenu"));

    menu->addMenu(menu1);
    menu->addMenu(menu2);

    w.show();
    return a.exec();
}

If I create a class for the menu bar, it does not appear. The only difference is that I've put the menu code in the constructor of the menu class and then instantiated the menu class from main.cpp:

main.cpp

#include <QtGui/QApplication>
#include "mainwindow.h"
#include "form.h"
#include "menu.h"


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;

    Menu m;
    m.show();

    w.show();
    return a.exec();
}

menu.h

#ifndef MENU_H
#define MENU_H

#include <QMenuBar>

class Menu : public QMenuBar
{
    Q_OBJECT

public:
    Menu(QMenuBar *parent = 0);
};

#endif // MENU_H

menu.cpp

#include "menu.h"

Menu::Menu(QMenuBar *parent)
{
    QMenuBar *menu = new QMenuBar(0);
    QMenu* menu1 = new QMenu("MENU1");
    menu1->addMenu(new QMenu("menu1_SubMenu"));

    QMenu* menu2 = new QMenu("MENU2");
    menu2->addMenu(new QMenu("menu2_SubMenu"));

    menu->addMenu(menu1);
    menu->addMenu(menu2);
}

What am I doing wrong?

Upvotes: 0

Views: 1050

Answers (1)

Sergei Tachenov
Sergei Tachenov

Reputation: 24919

Your Menu class is derived from QMenuBar, but you don't call any methods on it except show(). All addMenu() calls are made for the local variable menu in the constructor, which are allocated and then forgotten. You should call them on this instead:

#include "menu.h"

Menu::Menu(QMenuBar *parent)
{
    QMenu* menu1 = new QMenu("MENU1");
    menu1->addMenu(new QMenu("menu1_SubMenu"));

    QMenu* menu2 = new QMenu("MENU2");
    menu2->addMenu(new QMenu("menu2_SubMenu"));

    this->addMenu(menu1);
    this->addMenu(menu2);
}

Upvotes: 2

Related Questions