Qmenu addMenu returns derived class object

时间:2017-06-19 14:04:50

标签: qt qt4

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

1 个答案:

答案 0 :(得分:1)

QMenu::addMenu返回指向QMenu ...

的指针
QMenu *QMenu::addMenu(const QString &title);

因此,myMenu *的隐式向下转换将在以下内容中失败...

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

如果您想添加自己的自定义类型的子菜单,请使用提供该功能的QMenu::addMenu overload ...

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