首页 > 解决方案 > 触发时无法将 QAction 链接到函数(Qt 5)

问题描述

我正在尝试将上下文菜单添加到系统托盘(可通过单击系统托盘图标激活)我已成功添加菜单和带有文本“退出”的操作,但是我不知道如何链接“触发”的操作功能到另一个功能/更改触发功能或其他任何工作。我只是想在单击操作时激活某些特定行为。当我单击此操作按钮时,它不执行任何操作。我尝试使用此构造函数将其链接到成员函数:QAction *QMenu::addAction(const QIcon &icon, const QString &text, const QObject *receiver, PointerToMemberFunction method, const QKeySequence &shortcut = ...) 这是我的代码中最重要的部分:

     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);
    }

标签: c++qt5qaction

解决方案


addAction返回一个指向QAction对象的指针,获取该指针并用于在信号和槽connect之间建立连接:triggeredon_actionQuit_triggered

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

推荐阅读