Search code examples
c++qt5qaction

Unable to link QAction to a function when triggered (Qt 5)


I am trying to add a context menu to the system tray (activatable by clicking the system tray icon) I have successfully added the menu and an action with text "Exit", however I don't know how to link the actions "triggered" function to another function / change the triggered function or whatever else would work. I simply want to activate some particular behaviour when I click the action. This action button doesn't do anything when I click it. I tried linking it to a member function with this constructor: QAction *QMenu::addAction(const QIcon &icon, const QString &text, const QObject *receiver, PointerToMemberFunction method, const QKeySequence &shortcut = ...) Here is the most important segment of my code:

     MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        mSystemTrayIcon = new QSystemTrayIcon(this);
        mSystemTrayIcon->setIcon(QIcon(":/iris_logo.png"));
        mSystemTrayIcon->setVisible(true);

        systemTrayMenu = new QMenu("Context menu");
        systemTrayMenu->setToolTipsVisible(true);
 // I get the error: no matching member function for call to 'addAction'
        systemTrayMenu->addAction("Open", this, on_actionQuit_triggered())); 

// I dont get an error, however this only creates a menu button, not its corresponding function that must be called.
        systemTrayMenu->addAction("Exit"); 
        mSystemTrayIcon->setContextMenu(systemTrayMenu);
    }

Solution

  • addAction returns a pointer to QAction object, get this pointer and use connect to make the connection between triggered signal and on_actionQuit_triggered slot:

    QAction* openAction = systemTrayMenu->addAction("Open"); 
    connect (openAction, SIGNAL(triggered()) , this, SLOT(on_actionQuit_triggered()));