mac.ma
mac.ma

Reputation: 713

QMenu memory leak which everyone knows,but how to fix it?

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

Answers (4)

Heribert Scharnagl
Heribert Scharnagl

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

Kamil Klimek
Kamil Klimek

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

borges
borges

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

RazrFalcon
RazrFalcon

Reputation: 807

Try:

QMenu pRightKeyMenu;
pRightKeyMenu.exec(cur.pos());

Upvotes: 2

Related Questions