Search code examples
c++qtqt5contextmenuqlistwidget

QT context menu not aligned with cursor


When I right click, a context menu appears but it is not aligned with the cursor. I want the corner of the context menu to appear right where the cursor is. Here you can see it is quite far off to the right:

enter image description here

Here is the method where the context menu is shown:

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)); 

}

Thanks for the help!


Solution

  • The pos variable is relative to the viewport() of the QListWidget so you must use the mapToGlobal() method of the QListWidget:

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