QMenu position in QGraphicsScene
-
Hello, I'd like to display a QMenu when clicking on a button in a QGraphicsScene. I want to position the top-left menu corner at the center of the button but I cannot succeed doing it. Could you help me please ?
My QGraphicsScene :
QGraphicsGridLayout * grid = new QGraphicsGridLayout(); QGraphicsWidget * support = new QGraphicsWidget(); support->setLayout(grid); m_view->scene()->addItem(support); for() { QLabel * name = new QLabel(QString::fromStdString(b.getName())); QGraphicsProxyWidget * graphicsName = m_view->scene()->addWidget(name); grid->addItem(graphicsName, counter, 0, 1, 1, Qt::AlignVCenter | Qt::AlignLeft); QPushButton * button = new QPushButton(QIcon(":/icons/configuration.png"), ""); connect(button, SIGNAL(clicked()), this, SLOT(beamModificationMenu())); QGraphicsProxyWidget * graphicsButton = m_view->scene()->addWidget(button); grid->addItem(graphicsButton, counter, 1, 1, 1, Qt::AlignVCenter | Qt::AlignHCenter); counter++; }
And my function to display the menu :
void frequencyPlanRXConfiguration::modificationMenu() const { if(QPushButton * button = qobject_cast<QPushButton *>(sender())) { QMenu menu; menu.addAction("Action 1"); QAction * selectedItem = menu.exec(m_view->mapToGlobal(button->pos())); } }
-
Hi,
Out of curiosity, why not use the built in support for menu of QPushButton ?
It's not centered but it is integrated as the platform provides it.
-
Thanks SGaist, I just did not know this feature. That fits perfectly to my needs !
I tried this (removing signal and adding menu to the button) :
QPushButton * button = new QPushButton(QIcon(":/icons/configuration.png"), ""); QMenu myMenu; myMenu.addAction("Action 1"); myMenu.addAction("Action 2"); button->setMenu(&myMenu); //connect(button, SIGNAL(clicked()), this, SLOT(beamModificationMenu())); QGraphicsProxyWidget * graphicsButton = m_view->scene()->addWidget(button); grid->addItem(graphicsButton, counter, 1, 1, 1, Qt::AlignVCenter | Qt::AlignHCenter);
However, the button is just a bit larger (as if to display the little arrow toward bottom indicating a possible menu) but menu does not appear. Do I need to add someting (like a showMenu) ?
-
Your QMenu is on the stack and thus destroyed at the end of the function. Hence you can not see it.