Unsolved Custome Menu in Qmouseevent (Please review)
-
I have implemented custom menu in mouse event on Right button . Following is the code for the same . Can some let me know if there is better way to solve the problem
void myTableView::mousePressEvent(QMouseEvent* event) {
QTableView::mousePressEvent(event);
if (event->button() == Qt::RightButton) {
showContextMenu(event);
}
}/* Right click menu Copy*/
void myTableView::showContextMenu(QMouseEvent* event)
{
QMenu *menu= new QMenu(this);
menu->addAction(QObject::tr(Menu"), this, SLOT(func()));
menu->exec(event->globalPos());
}void myTableView:func() {
}
-
Hi
There are also event for it
http://www.setnode.com/blog/right-click-context-menus-with-qt/myWidget->setContextMenuPolicy(Qt::CustomContextMenu);
connect(myWidget, SIGNAL(customContextMenuRequested(const QPoint&)),
this, SLOT(ShowContextMenu(const QPoint&))); -
@Qt-Enthusiast said:
void myTableView::mousePressEvent(QMouseEvent* event) {
QTableView::mousePressEvent(event);
if (event->button() == Qt::RightButton) {
showContextMenu(event);
}
}/* Right click menu Copy*/
void myTableView::showContextMenu(QMouseEvent* event)
{
QMenu *menu= new QMenu(this);
menu->addAction(QObject::tr(Menu"), this, SLOT(func()));
menu->exec(event->globalPos());
}void myTableView:func() {
}
One question do you see any issue in my implementation ? is there is any issue/problem in the code
void myTableView::mousePressEvent(QMouseEvent* event) {
QTableView::mousePressEvent(event);
if (event->button() == Qt::RightButton) {
showContextMenu(event);
}
}/* Right click menu Copy*/
void myTableView::showContextMenu(QMouseEvent* event)
{
QMenu *menu= new QMenu(this);
menu->addAction(QObject::tr(Menu"), this, SLOT(func()));
menu->exec(event->globalPos());
}void myTableView:func() {
}
about an hour ago Reputation: 0 | Posts: 82
-
Well , you create the menu on each showContextMenu
so its a memory leak
after exec()
u should delete -
I think what you say is like this
/* Right click menu Copy*/
void myTableView::showContextMenu(QMouseEvent* event)
{
QMenu *menu= new QMenu(this);
menu->addAction(QObject::tr(Menu"), this, SLOT(func()));
menu->exec(event->globalPos());
delete menu;}
Also do we need to put event-accept like as shown in the code below
void myTableView::mousePressEvent(QMouseEvent* event) {
QTableView::mousePressEvent(event);
if (event->button() == Qt::RightButton) {
showContextMenu(event);
}
}
/* Right click menu Copy*/
void myTableView::showContextMenu(QMouseEvent* event)
{
QMenu *menu= new QMenu(this);
menu->addAction(QObject::tr(Menu"), this, SLOT(func()));
menu->exec(event->globalPos());
delete menu;
event->accept
}
void myTableView:func() {
} -
Hi,
To add to @mrjj, looking at the lifetime of your menu there's no need to allocate it on the heap, just do it on the stack so it will get destroyed automatically when the function ends.