M.M
M.M

Reputation: 141576

findChild does not find menu just added to a QMenuBar

Here is my code snippet:

void MainWindow::on_TestButton_triggered()
{
    QMenu *m = menuBar()->addMenu("TestMenu");

    auto *found = menuBar()->findChild<QMenu *>("TestMenu");
    if ( !found )
        MessageBox(NULL, "not found", "s", MB_OK);
}

It always produces the MessageBox. What can I do instead to get a pointer (or other handle) of an existing menu in the bar?

The ultimate goal of this is to be able to find and delete menus that were added in a different code block, so "just use m" would not be a solution. I have a workable solution by maintaining an external vector of the return value of addMenu but would like something a bit more elegant.

Upvotes: 2

Views: 329

Answers (1)

eyllanesc
eyllanesc

Reputation: 243965

findChild uses the objectName to do the search but in your case QMenu does not have an objectName, so the solution is to set the objetctName:

QMenu *m = menuBar()->addMenu("TestMenu")
m->setObjetctName("TestMenu");

Upvotes: 5

Related Questions