1

I have a "Recent files" file menu as QMenu, like: File-->Recent files. In that I create dynamically several QActions with the recently opened files listed. That works.

But I want to trigger a seperate SLOT when I click on that Recent files QMenu.

connect(ui->menuRecently_Open, SIGNAL(triggered(QAction*)), this, SLOT(onRecentOpenFiles(QAction*)));

and a TRIGGER debug message should printed out

void MainWindow::onRecentOpenFiles(QAction* action)
{
  qDebug() << "TRIGGER";
}

But nothing happens ?

Ralf Wickum
  • 2,850
  • 9
  • 55
  • 103
  • May be the reason is: [This signal is emitted for the main parent menu in a hierarchy. Hence, only the parent menu needs to be connected to a slot; sub-menus need not be connected.](http://doc.qt.io/qt-5.5/qmenu.html#triggered). – Amartel Aug 05 '15 at 12:03
  • @Amartel so its parent is the "File" which is also a QMenu. But how could I solve that then? – Ralf Wickum Aug 05 '15 at 12:15
  • Well, you could connect to `ui->menuFile`. – Amartel Aug 05 '15 at 12:23
  • @Amartel That does not change anything. I can not trigger that slot, just by clicking on a QMenu. – Ralf Wickum Aug 06 '15 at 09:05
  • 1
    possible duplicate of [How to perform action on clicking a QMenu object only?](http://stackoverflow.com/questions/22197496/how-to-perform-action-on-clicking-a-qmenu-object-only) – Murat Aug 06 '15 at 09:16

2 Answers2

3

This works as expected:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    setupUi(this);

    QMenu *fileMenu = menuBar()->addMenu(tr("File"));
    QMenu *recentMenu = fileMenu->addMenu(tr("Recent"));
    recentMenu->addAction(tr("File1"));
    recentMenu->addAction(tr("File2"));
    recentMenu->addAction(tr("File3"));

    connect(recentMenu, SIGNAL(triggered(QAction*))
            , SLOT(onRecentOpenFiles(QAction*)));
}

void MainWindow::onRecentOpenFiles(QAction *action)
{
    qDebug() << action;
}

And you are doing something wrong, or not telling us everything.

Amartel
  • 4,248
  • 2
  • 15
  • 21
  • I have it exactly the same way as you have in your example, except for one thing: I added the fileMenu in the Qt Creator design mode. – Ralf Wickum Aug 26 '15 at 15:41
0

I met same problem, and I found I didn't add slot funciton under "private slots:" but to "private".

  • Hi, and welcome to Stack Overflow! Your answer could be improved with more details and clarification. See [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) in the [help center](https://stackoverflow.com/help). – Abderrahmene Rayene Mihoub May 23 '23 at 12:39