Search code examples
c++qtlazy-initializationqmenu

Qt QMenu lazy initialization


In my QMenu I have a submenu that may contain potentially hunderds of items, and it is not always used, so I am considering initalizing it only on demand:

The menu in question

I suspect that this can be done by implementing a QAbstractItemModel and overriding the methods canFetchMore fetchMore.

Is there an easier way using some trick? I don't mind if it is a little hackish (like replacing a dummy menu after clicking it with the good one, or something like that).


Solution

  • A hackish way, but it works well in my initial tests, would be something like:

    //    menuBar->addMenu(Slow::APIMenu()); //old way
    
        auto emptyApiMenu = new QMenu("API");
        emptyApiMenu->addAction("API"); //dummy item to avoid qt warning of invisible menu
        QObject::connect(emptyApiMenu, &QMenu::aboutToShow, [=]() //lazy initialization of API menu
        {
            menuBar->insertMenu(emptyApiMenu->menuAction(), Slow::APIMenu());
            menuBar->removeAction(emptyApiMenu->menuAction());
        });
        menuBar->addMenu(emptyApiMenu);
    

    It even opens the recently spawned menu so it is seamless