nocturne nocturne - 19 days ago 6
C++ Question

Qt - connect menuBar and QWidget

So I have menu bar like this:

this->layout = new QGridLayout;
QMenuBar* menuBar = new QMenuBar();
QMenu *fileMenu = new QMenu("File");
menuBar->addMenu(fileMenu);
fileMenu->addAction("Exit");
this->layout->setMenuBar(menuBar);


And I am wonderig how to connect thie action
"Exit"
with some slot my
QWidget
, I tryed something like this:

connect(menuBar,SIGNAL(menuBar->actions),this,SLOT(exitGame()));


But it is not working, can you tell me what I am doing wrong? And yes I have read manual about QMenuBar bud there are no examples of connecting. I have read about some connecting in Qt Designer but I am not using it.

Answer

You need to connect the QAction pointer returned from QMenuBar::addAction to the slot...

auto *exit_action = fileMenu->addAction("Exit");
connect(exit_action, &QAction::triggered,
        [this](bool checked)
        {
          exitGame();
        });