使用QMenu并传递参数

Working with a QMenu and passing of arguments

本文关键字:参数 QMenu 使用      更新时间:2023-10-16

我有一个QMenu,它有几个动态构建的菜单项。

为此,我迭代了一组菜单项,其中包含名称和Action(如果菜单项被击中,则需要执行此操作),并不断将它们添加到上下文菜单中。所有菜单项都需要连接到一个公共插槽

但不知何故,触发动作并没有发生。即到达connect语句,但控制没有传递到指定的SLOT,不采取任何操作。

for (int i=0; i<Action_List.size();i++)
{
    tempAct1 = Action_List.at(i); //Action List has the list of Actions
    Context_Menu->addAction(tempAct1);
}
if (Context_Menu!=NULL) {
    Context_Menu->exec(QCursor::pos());
    int r = connect(Context_Menu, SIGNAL(triggered(QAction *)), 
                    this, SLOT(SPlusCommand(QAction *)));
}
int P14MainWindow::SPlusCommand ( QAction* Action)
{
    QVariant tempstr = Action->data();
    QString Qs = tempstr.toString();
    return QPwLocalClient::ExecuteCommand(Qs);
}

有人能告诉我这个哪里不对吗?

似乎应该在exec():之前移动connect

connect(Context_Menu, SIGNAL(triggered(QAction *)), 
        this, SLOT(SPlusCommand(QAction *)));
Context_Menu->exec(QCursor::pos());

因为exec同步执行菜单,这意味着只有当你与菜单的所有交互完成时,它才会从这个方法返回——太晚了,无法连接它之后的东西。

您必须将各个操作与插槽连接起来。

connect(action, SIGNAL(triggered()), this, SLOT(yourSlot())