Techi Techi
Techi Techi

Reputation: 63

findChild of QMenu does is not working properly

findChild of QMenu is not working properly.

Following is the code for you

QMenu* lMenu;
QMenu* existingMenu = lMenu->findChild<QMenu*>(QString("A..."));
if (!existingMenu)
  lMenu->addMenu("A...");

I am getting the existing menu as NULL even if the menu for string A is already present

Upvotes: 1

Views: 903

Answers (2)

eyllanesc
eyllanesc

Reputation: 244282

The method findChild() searches for the objectName and not for the title, in your case the sub-menus do not have a name so it returns an empty list, so what you should do is filter the QMenus first and then do a second filter with the titles:

#include <algorithm>

...

QString text("A...");    
// get sub-menus
QList<QMenu *> sub_menus = lMenu->findChildren<QMenu *>();
// filter by title
if(std::find_if(sub_menus.begin(), sub_menus.end(),
                [text] (QMenu *menu){ return menu->title() == text; }) == sub_menus.end())
{
    lMenu->addMenu("A...");
}

Upvotes: 3

JustWe
JustWe

Reputation: 4484

If you want to use findChild, have to consider QMenu as a QObject. Because the function is for searching the QObject but not QMenu.

Demo:

QMenu* menu = new QMenu;
QMenu* subMenu = new QMenu("subMenu", menu); // second parameter indicate menu is the parent qobject of subMenu
subMenu->setObjectName("subMenu object name"); // give submenu a qobject name for findChild 
menu->addMenu(subMenu);

if(menu->findChild<QMenu*>("subMenu object name") == subMenu) {
    qDebug()<<"Find subMenu";
}

Upvotes: 2

Related Questions