下面我引用了我的代码。这个问题很容易描述。 selectedItem-> text不是区分菜单中选择的操作的正确方法。怎么做对?

void RView::ShowContextMenu(const QPoint& pos) // this is a slot
{
// for most widgets
QPoint globalPos = statusWidget->mapToGlobal(pos);
// for QAbstractScrollArea and derived classes you would use:
// QPoint globalPos = myWidget->viewport()->mapToGlobal(pos);

QMenu myMenu;
myMenu.addAction("first");
myMenu.addAction("second");

QAction* selectedItem = myMenu.exec(globalPos);
if (selectedItem)
{
    if(selectedItem->text == "first")
     // do something
    if(selectedItem->text == "second")
     // do other stuff
}
else
{
    // nothing was chosen
}
}

最佳答案

您应该直接比较QAction,或者像在selectedItem中那样使用if的比较,或者最好将每个 Action 都连接到所需的广告位(或lambda,如果它们是本地化到此上下文的话)。

QMenu myMenu;
QAction *action1 = myMenu.addAction("first");
QAction *action2 = myMenu.addAction("second");
connect(action1, &QAction::triggered, [](){/*lambda code here*/});
connect(action2, &QAction::triggered, [](){/*lambda code here*/});
myMenu.exec(statusWidget->mapToGlobal(pos));

编辑:对于Qt4,您将使用插槽和旧的连接语法:
QMenu myMenu;
QAction *action1 = myMenu.addAction("first");
QAction *action2 = myMenu.addAction("second");
connect(action1, SIGNAL(triggered()), this, SLOT(doStuff()));
connect(action2, SIGNAL(triggered()), this, SLOT(doOtherStuff()));
myMenu.exec(statusWidget->mapToGlobal(pos));

为此,您需要将“doStuff”和“doOtherStuff”声明为 header 中不带任何参数的插槽(因为信号QAction::triggered()没有)。您要完成的代码将转到这些插槽的定义:
class RView
{
public slots:
    void doStuff() { /*do stuff*/ }
    void doOtherStuff() { /*do other stuff*/ }
};

关于c++ - 确定QAction的触发因素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40821651/

10-14 07:50