Search code examples
c++qtsignals-slots

Connect QAction to nonmember-qt function in Qt5


I want to add a button to my TrayIcon (in Qt5.5) . (I'm using QMenu, QAction) When I click it I would like to call public Non-Qt function. How to connect to this SIGNAL?

mainwindow.h:
private:
    void tray();
    QMenu *trayIconMenu;
    QAction *ExampleAction;

mainwindow.cpp:

    void exfunction()
    {
    }

    void MainWindow::tray()
    {
        ExampleAction = new QAction(tr("Sample Text"), this);
        connect(ExampleAction,SIGNAL(triggered()), exfunction()); //How to propertly connect it? 

        trayIconMenu = new QMenu(this);
        trayIconMenu->addAction(ExampleAction);
    }

Solution

  • In Qt 5 you can connect to a regular member function, to a free function or a lambda expression, but you must use the new syntax

    connect(ExampleAction, &QAction::triggered, exfunction);