Pop-up menu only appears on screen top left corner
-
Hello, very new to this. If someone could please point me the right direction (or offer a solution) it would be much appreciated.
I'm using Qt Creator to create the ui of an application. Using mingw on Windows 7 os... I do not have any MS software with compilers.
Within the application there is a modified tree view widget where I am trying to have a context menu appear when right-clicked... and at the location of the click. So far - with one exception - the menu always appears at the top left corner of my computer screen regardless of where the application appears or is moved. The one exception is when the menu coordinates are hard coded. How to make it appear where the mouse is clicked?
Code below:
@#include "modqtreeview.h"
#include <QMouseEvent>
#include <QMenu>
#include <QPoint>modQTreeView::modQTreeView(QWidget *parent) : QTreeView(parent)
{
installEventFilter(this);
}bool modQTreeView::eventFilter(QObject *obj, QEvent *event)
{
if(event->type() == QEvent::ContextMenu)
{
QMouseEvent mouseEvent = static_cast<QMouseEvent> (event);
QMenu *menu = new QMenu(this);
menu->addAction(new QAction("New",this));
menu->addAction(new QAction("Edit",this));
menu->addAction(new QAction("Delete",this));
//QPoint xy = QPoint(mouseEvent->pos().x(), mouseEvent->pos().y()); // same top left corner with this
//QPoint xy = QPoint(200, 500); // position hard coding worked
//menu->move(xy);
menu->pos() = mouseEvent->globalPos();
menu->exec();
return false;
}
else
return QTreeView::eventFilter(obj, event);
}@ -
@
// replace these two lines
menu->pos() = mouseEvent->globalPos();
menu->exec();
// with this
menu->exec(event->globalPos());
@@
// This line does nothing, pos() is for reading
menu->pos() = mouseEvent->globalPos();
@ -
Seamus,
Thank You for the suggestion. The build came back with:
'class QEvent' has no member named 'globalPos'
Since then tried:
@menu->move(mouseEvent->pos());@
then:
@menu->move(mouseEvent->globalPos());@
followed by:
@menu-> exec();@
Still showing menu in top left corner of screen when using those.
Steven
-
And the solution is......................
@#include "modqtreeview.h"
#include <QMouseEvent>
#include <QMenu>
#include <QCursor> // added in to use QCursor belowmodQTreeView::modQTreeView(QWidget *parent) : QTreeView(parent)
{
installEventFilter(this);
}bool modQTreeView::eventFilter(QObject *obj, QEvent *event)
{
if(event->type() == QEvent::ContextMenu)
{
QMouseEvent mouseEvent = static_cast<QMouseEvent> (event);
QMenu *menu = new QMenu(this);
menu->addAction(new QAction("Add Data",this));
menu->addAction(new QAction("Add Group",this));
menu->addAction(new QAction("Add New View",this));
menu->exec(QCursor::pos()); // makes pop-up menu appear at location where mouse is clicked
return false;
}
else
return QTreeView::eventFilter(obj, event);
}@
A wonderfully simple solution inspired by a posting elsewhere.Steven