Reputation: 713
I have this code in a slot function.
QCursor cur=this->cursor();
QMenu* pRightKeyMenu=new QMenu(this);
pRightKeyMenu->popup(cur.pos());
When I click the right mouse key, it will be invoked. After that, I find that memory is going up up up... and never goes down. How can I fix that?
Upvotes: 1
Views: 1646
Reputation: 147
To avoid any leak, add the QMenu as QScopedPointer to your class and instantiate the menu in the class constructor.
class Widget : public QWidget
{
...
private:
QScopedPointer<QMenu> _myMenu;
}
Widget::Widget()
{
...
_myMenu.reset(new QMenu(this));
_myMenu->addAction("Some menuitem..", this, SLOT(menuItemActivated()));
}
Upvotes: 3
Reputation: 13130
Also you could do:
QCursor cur=this->cursor();
QMenu* pRightKeyMenu=new QMenu(this);
connect(pRightKeyMenu, SIGNAL(aboutToHide()), pRightKeyMenu, SLOT(deleteLater()));;
pRightKeyMenu->popup(cur.pos());
Upvotes: 5
Reputation: 3687
The variable pRightKeyMenu
is leaking because you're not releasing it.
One possible solution is to reuse it, since, by your code, the created QMenu is always the same:
Widget::Widget()
{
// ...
this->pRightKeyMenu = new QMenu(this);
}
// Slot
void Widget::contextMenu()
{
QCursor cur=this->cursor();
this->pRightKeyMenu->popup(cur.pos());
}
Upvotes: 2