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

ContextMenu not working when using Qt::ActionsContextMenu and static memory allocation



  • Hello,

    I hope someone could explain me this behaviour, when using setContextMenuPolicy(Qt::ActionsContextMenu).
    I can see my QActions in the contextMenu but only when I create them using dynamic memory allocation, like the 3 first. If i use static memory allocation (like the last one) the QAction is not showed in the contextMenu.

    MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
    
        QAction *searchTodayAction = new QAction("Today's Flight", this);
        QAction *searchYesterdayAction = new QAction("Yesterday's Flight", this);
        QAction *randomAction = new QAction("Random Flight", this);
        QAction notWorkingAction("Stuck Flight", this);
    
        this->addAction(searchTodayAction);
        this->addAction(searchYesterdayAction);
        this->addAction(randomAction);
        this->addAction(&notWorkingAction);
        this->setContextMenuPolicy(Qt::ActionsContextMenu);
    }
    

    Thanks !


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Because notWorkingAction is a variable local to the constructor, so it will be destroyed at the end of it.


  • Lifetime Qt Champion

    Hi
    Its not a static allocation, its stack allocation and its
    deleted when scope ends. in this case the constructor.


Log in to reply