You should implement an eventFilter
for your QMenu
. In the eventFilter
method, you need to calculate the position where your menu will be shown.
Here you have an example:
.pro
TEMPLATE = app
QT += widgets
SOURCES += main.cpp \
dialog.cpp
HEADERS += dialog.h
FORMS += dialog.ui
main.cpp
#include <QtWidgets/QApplication>
#include "dialog.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog dia;
return dia.exec();
}
dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QtWidgets/QDialog>
#include <QMenu>
#include "ui_dialog.h"
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog();
protected:
bool eventFilter(QObject * obj, QEvent *event);
private:
QMenu *menu;
Ui::Dialog m_ui;
};
#endif
dialog.cpp
#include "dialog.h"
Dialog::Dialog()
{
m_ui.setupUi(this);
menu = new QMenu("menu", this);
menu->installEventFilter(this);
QAction *action = new QAction("action#1", this);
menu->addAction(action);
m_ui.pushButton->setMenu(menu);
}
bool Dialog::eventFilter(QObject * obj, QEvent *event)
{
if (event->type() == QEvent::Show && obj == m_ui.pushButton->menu())
{
int menu_x_pos = m_ui.pushButton->menu()->pos().x();
int menu_width = m_ui.pushButton->menu()->size().width();
int button_width = m_ui.pushButton->size().width();
QPoint pos = QPoint(menu_x_pos - menu_width + button_width,
m_ui.pushButton->menu()->pos().y());
m_ui.pushButton->menu()->move(pos);
return true;
}
return false;
}
QPushButton* b
in classPopupMenu
? And is it theshowEvent
function will be called every time I click the Push Button for the PopupMenu ? – Skimp