首页 > 解决方案 > QT 上下文菜单未与光标对齐

问题描述

当我右键单击时,会出现一个上下文菜单,但它没有与光标对齐。我希望上下文菜单的角落出现在光标所在的位置。在这里你可以看到它离右边很远:

在此处输入图像描述

这是显示上下文菜单的方法:

void MainWindow::on_listWidget_customContextMenuRequested(const QPoint &pos)
{

    QMenu menu("contextMenu", this);
    QAction deleteItem("Delete", this);
    menu.addAction(&deleteItem);
    connect(&deleteItem, SIGNAL(triggered()), this, SLOT(deleteItem()));
    menu.exec(mapToGlobal(pos)); 

}

谢谢您的帮助!

标签: c++qtqt5contextmenuqlistwidget

解决方案


pos变量是相对于viewport()QListWidget所以你必须使用的mapToGlobal()方法QListWidget

menu.exec(ui->listWidget->viewport()->mapToGlobal(pos));

推荐阅读