1

I have a Qt project with a QMainWindow, which has the following actions and slots:

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = Q_NULLPTR);

private:
    Ui::MainWindowClass ui;
    //..... other code

    QMenu* fileMenu;
    QAction* newAct; //The concerned QAction*
    
public slots:

    void newGame();//The concerned slot

    //..... other code
};

I have initialized and connected the QAction and slot in the MainWindow's constructor:

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
    
   //...... other code

    newAct = new QAction(tr("&New Game"), this);
    newAct->setShortcut(QKeySequence::New);
    connect(newAct, &QAction::triggered, this, &MainWindow::newGame);
    
    fileMenu = menuBar()->addMenu(tr("&File"));
    fileMenu->addAction(newAct);

    //..... other code
}

When I run the application, the QAction newAct shows up in the menu bar, but when it is clicked, nothing happens. The slot work fine, when it is invoked in another part of the code, so I know that the slot works fine. For some reason, I suspect that QAction being triggered isn't calling the NewGame() slot.

Is there anything I'm missing in here?

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • Can you check if the return value of `connect(newAct, &QAction::triggered, this, &MainWindow::newGame);` is true or false. If its false then your connection is not valid. – sonulohani Jul 29 '20 at 05:59

1 Answers1

1

your code with the QAction, Shortcut and Connect looks fine so am suspecting of the slot newGame in the mainWindow I did try on my system with a lambda like

connect(newAct, &QAction::triggered, []()
{
    qDebug()<< "Hello Action";
});

and I can see the HelloAction when clicking and when using the shortcut ctrl+N

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • I altered the slot and found out that it was indeed connecting and executing itself when QAction was triggered. For some reason, it behaved differently. – CharlieKeith Jul 29 '20 at 06:38