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?
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