Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

MenuBar - why it doesn't work?



  • Hi, I wrote this code:

    editor = new QTextEdit;
    setCentralWidget(editor);
    menu = new QMenuBar;
    listOfMenus = new QMenu[2];
    listOfMenus[0].setTitle("File");
    listOfMenus[1].setTitle("Edit");
    QString textes[] = {"New","Open","Save","Save as", "Print", "Exit",
                       "Undo", "Redo", "Copy","Paste","Cut"};
    QString icons[] = {"new","open","save","save","print","exit",
                      "undo", "redo", "copy", "paste", "cut"};
    
    QAction actions[11];
    
    for(int i=0; i<11; i++){
        actions[i].setIcon(QIcon(QString(":/Images/" + icons[i])));
        actions[i].setText(textes[i]);
    }
    
    for(int i=0; i<6; i++)
        listOfMenus[0].addAction(&actions[i]);
    
    for(int i=6; i<11; i++)
        listOfMenus[1].addAction(&actions[i]);
    
    menu->addMenu(listOfMenus);
    menu->addMenu(&listOfMenus[1]);
    menu->setVisible(true);
    setMenuBar(menu);
    

    It sets values of actions and then adds them into menus;
    and finally, menus are added to menu bar

    Unfortunately, code doesn't work... Do you know what's wrong?


  • Lifetime Qt Champion

    Hi
    I think you action runs out of scope

    it seems to be local variable
    QAction actions[11];

    and you take address of them so it does not copy but refernce inside the list
    listOfMenus[0].addAction(&actions[i]);

    but it looks to me like the actions[11]; lives in constructor and hence
    when Mainwindow is shown, they are all already deleted.

    Move the list to be a member of the class and see.

    Damn Pl45m4 beat me to it :)



  • @amy-cpp

    Hi,

    what exactly does not work?

    Better use container types like QList or QVector instead of std::arrays to store QObjects.



  • @Pl45m4 Code creates menu bar, and menus 1 and 2, but doesn't add actions to menus



  • @amy-cpp

    Create QActions on heap and use pointers.


  • Lifetime Qt Champion

    Hi
    I think you action runs out of scope

    it seems to be local variable
    QAction actions[11];

    and you take address of them so it does not copy but refernce inside the list
    listOfMenus[0].addAction(&actions[i]);

    but it looks to me like the actions[11]; lives in constructor and hence
    when Mainwindow is shown, they are all already deleted.

    Move the list to be a member of the class and see.

    Damn Pl45m4 beat me to it :)