Sijith
Sijith

Reputation: 3932

Qmenu addMenu returns derived class object

I have a class which is derived from QMenu but ia m not able to return the derive class object

myMenu * editMenu = new myMenu(); // myMenu is derived from QMenu
myMenu *preferenceMenu = new myMenu();
preferenceMenu  = editMenu->addMenu(tr("&Preferences")); // this shows error

QMenu *preferenceMenu = new QMenu();
preferenceMenu  = editMenu->addMenu(tr("&Preferences")); // this works fine

Upvotes: 0

Views: 120

Answers (1)

G.M.
G.M.

Reputation: 12879

QMenu::addMenu returns a pointer to a QMenu...

QMenu *QMenu::addMenu(const QString &title);

So the implicit downcast to myMenu * will fail in the following...

myMenu *preferenceMenu = editMenu->addMenu(tr("&Preferences"));

If you want to add a submenu of your own custom type then use the QMenu::addMenu overload that provides that functionality...

auto *preferences_menu = new myMenu(tr("&Preferences");
editMenu->addMenu(preferences_menu);

Upvotes: 1

Related Questions