设置 Qt QPushButton 弹出菜单的位置(向右)

Set position (to right) of Qt QPushButton popup menu(设置 Qt QPushButton 弹出菜单的位置(向右))
本文介绍了设置 Qt QPushButton 弹出菜单的位置(向右)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 Qt 按钮小部件编写弹出菜单.每当单击按钮时,都会弹出一个菜单(在按钮下方).

I am writing a popup menu for a Qt push button widget. Whenever the push button is clicked, a menu pops up (below the push button).

弹出菜单默认在左侧下方.

The popup menu is left-sided below by default.

有什么方法可以让弹出菜单在右侧按钮下方弹出?

Are there any ways to make the popup menu to pop up on the right side below the push button?

没有设置位置功能,不知道有没有什么复杂的方法呢?

There is no set position function, so I wonder if there is some sophisticated way of doing it?

这是一些代码(用于弹出菜单):

Here is some code (for popup menu):

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

推荐答案

这可以通过继承 QMenu 并将弹出菜单移动到 showEvent 中您想要的位置来完成:

This can be done by subclassing QMenu and moving the popup menu where you want to have it in 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());
}

ma​​inwindow.cpp

...
PopupMenu* menu = new PopupMenu(ui->pushButton, this);
...
ui->pushButton->setMenu(menu);

看起来像这样:

这篇关于设置 Qt QPushButton 弹出菜单的位置(向右)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)