使用环境 Linux Qt5.13.0 (理论上windows端也可以用),主要代码如下,自己加到工程里边就可以
menuBar()->actionGeometry(action):获取菜单项在菜单栏中的几何位置。
menuBar()->mapToGlobal(actionRect.bottomLeft()):将菜单项的左下角位置转换为全局坐标。
QShortcut *shortcut_W = new QShortcut(QKeySequence("Alt+W"), this);
connect(shortcut_W, &QShortcut::activated, this, &MainWindow::showPopupMenu_W);
void MainWindow::showPopupMenu_W()
{
QAction *action = menu_W->menuAction();
QRect actionRect = menuBar->actionGeometry(action);//获取菜单项在菜单栏中的几何位置
QPoint menuPos = menuBar->mapToGlobal(actionRect.bottomLeft());//将菜单项的左下角位置转换为全局坐标。
// 调整菜单位置,使其与鼠标点击时一致
menuPos.setY(menuPos.y() + 1); // 根据实际需要微调位置
// 打印或获取子菜单的坐标
// qDebug() << "Menu H will pop up at:" << menuPos;
// 使用 QTimer 来模拟弹出效果,避免阻塞事件循环
QTimer::singleShot(0, this, [this, menuPos]()
{
menu_W->popup(menuPos);
});
}