I allow custom context menu to appear over a table. This is how the menu is generated, using a generic function that accepts target widget and coordinates:
#include <QMenu>
void MainWindow::makeContextMenu(const QPoint& pos, QWidget* target)
{
QMenu *menu = new QMenu(this);
menu->addAction(new QAction("Action 1", menu));
menu->addAction(new QAction("Action 2", menu));
menu->addAction(new QAction("Action 3", menu));
// Notify window about clicking
QObject::connect(menu, &QMenu::triggered, this, &MainWindow::menuClicked);
// If this is a scroll area, map coordinates to real app coordinates
if(QAbstractScrollArea* area = dynamic_cast<QAbstractScrollArea*>(target))
menu->popup(area->viewport()->mapToGlobal(pos));
else
menu->popup(pos);
}
The problem is that the QMenu* menu
never gets destroyed and removed from memory. It persists as MainWindow
's child even after it's hidden.
What should I do? Can I set the menu to delete itself? Or should I reuse the same instance of menu or maybe save it into same pointer?