我正在尝试创建一个弹出菜单,可以在其中检测到给定项目的鼠标按钮。我创建了一个自定义 QAction 已经建立了我的 QMenu, ,但是 triggered 按下菜单项时的信号未提供 QMouseEvent 让我查询按下按钮。

另外,我为每个设置一个状态提示 QAction, ,当我鼠标鼠标时出现在状态栏中,但即使我关闭了 QMenu. 。这是正常的行为吗?

有帮助吗?

解决方案

我不确定我是否了解您想要什么;但是,如果您想在右键单击上显示一个弹出菜单,则首先应在窗口小部件(或窗口类)的标头文件中覆盖与鼠标事件相关的函数,并声明某些功能会显示您的弹出菜单。因此,标题文件应包含以下声明:

...
void Popup(const QPoint& pt);
void mousePressEvent(QMouseEvent *event);
...

在CPP文件的函数定义中:

void testQt::mousePressEvent(QMouseEvent *event)
{
     if (event->button() == Qt::RightButton) {

         this ->Popup(event ->pos());
         event->accept();
     }
 }

void testQt::Popup(const QPoint& pt)
{
    QPoint global = this ->mapToGlobal(pt);
    QMenu* pPopup = new QMenu(this);

    QAction* pAction1 = new QAction("Item 1", this);
    QAction* pAction2 = new QAction("Item 2", this);
    pPopup ->addAction(pAction1);
    pPopup ->addAction(pAction2);

    QAction* pItem = pPopup ->exec(global);

    if(pItem == pAction1)
    {
    }
    else if(pItem == pAction2)
    {
    }
}

现在,当您按右键按钮时,弹出菜单将出现在光标的位置。我希望这有帮助。

注意:如果选择选择操作时按下哪个鼠标按钮,则应从qmenu继承自己的类。 Qmenu类包含受保护的功能 mousePressEvent(QMouseEvent *event) 它应该被过度放大,您可以检测到菜单中选择项目时按下左或右鼠标按钮。

其他提示

我知道这是一个非常古老的帖子。但是,如果您想知道在弹出菜单/上下文菜单中单击的按钮。假设您按下按钮保存,它与信号和插槽等连接。在插槽调用中 sender();. 。这返回a QObject 您可以将其投入到您的 QAction* 并从中获取数据等。

void MyClass::showMenu()
{
     auto action(new QAction*("Blah", ui->my_toolbar));

     QObject::connect(action, &QAction::triggered, this, &MyClass::mySlot);
}

void MyClass::mySlot()
{
     auto myAction(static_cast<QAction*>(sender()));
     myAction->doAwesomeStuff();
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top