我正在为Qt按钮小部件编写一个弹出菜单。只要单击按钮,就会弹出一个菜单(按钮下方)。
默认情况下,弹出式菜单位于左下方。
有没有办法让弹出菜单弹出按钮下方的右侧?
没有设定位置功能,所以我想知道是否有一些复杂的方法呢?
这是一些代码(用于弹出菜单):
QMenu *menuMode = new QMenu(this);
min = menu ->addAction("In");
mout = menu ->addAction("out");
ui->pushButtonMode->setMenu(menuMode); //I am writing in MainWindow, that's there is ui
答案 0 :(得分:6)
这可以通过继承QMenu并将弹出菜单移动到showEvent
所需的位置来完成:
<强> popupmenu.h 强>
#ifndef POPUPMENU_H
#define POPUPMENU_H
#include <QMenu>
class QPushButton;
class QWidget;
class PopupMenu : public QMenu
{
Q_OBJECT
public:
explicit PopupMenu(QPushButton* button, QWidget* parent = 0);
void showEvent(QShowEvent* event);
private:
QPushButton* b;
};
#endif // POPUPMENU_H
<强> popupmenu.cpp 强>
#include "popupmenu.h"
#include <QPushButton>
PopupMenu::PopupMenu(QPushButton* button, QWidget* parent) : QMenu(parent), b(button)
{
}
void PopupMenu::showEvent(QShowEvent* event)
{
QPoint p = this->pos();
QRect geo = b->geometry();
this->move(p.x()+geo.width()-this->geometry().width(), p.y());
}
<强> mainwindow.cpp 强>
...
PopupMenu* menu = new PopupMenu(ui->pushButton, this);
...
ui->pushButton->setMenu(menu);
看起来像这样:
答案 1 :(得分:1)
您应为eventFilter
实施QMenu
。在eventFilter
方法中,您需要计算菜单的显示位置。
这里有一个例子:
<强>的.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;
}
答案 2 :(得分:0)
另一种(imho)更简单的方法是:
void MainFrame::Slot_ShowMenu()
{
auto pMenu = new QMenu(this);
connect(pMenu, &QMenu::aboutToHide, pMenu, &QMenu::deleteLater);
...
// Retrieve a valid width of the menu. (It's not the same as using "pMenu->width()"!)
int menuWidth = pMenu->sizeHint().width();
int x = mUI.myQPushButton->width() - menuWidth;
int y = mUI.myQPushButton->height();
QPoint pos(mUI.myQPushButton->mapToGlobal(QPoint(x, y)));
pMenu->popup(pos);
}