代码之家  ›  专栏  ›  技术社区  ›  mrg95

更改QMenu中子菜单的位置

  •  1
  • mrg95  · 技术社区  · 8 年前

    在我的项目中,我有一个带有子菜单项的QMenu。子菜单有很多项,所以它的高度相对较大。

    我想相对于执行子菜单的项目垂直居中子菜单。

    我已经对我要重新定位的子菜单进行了子类化,并尝试在“aboutToShow”上更改几何图形以进行测试,但这没有任何效果:

    class MySubMenu : public QMenu
    {
        Q_OBJECT
    public:
        QuickMod();
        ~QuickMod();
    
    private slots:
        void centerMenu();
    };
    
    
    
    MySubMenu::MySubMenu()
    {
        connect(this, SIGNAL(aboutToShow()), this, SLOT(centerMenu()));
    }
    
    MySubMenu::~MySubMenu()
    {
    }
    
    void MySubMenu::centerMenu()
    {
        qDebug() << x() << y() << width() << height();
        setGeometry(x(), y()-(height()/2), width(), height());
    }
    

    这是我快速绘制的一幅图像,我希望它能直观地解释我想要实现的目标:(之前和之后) enter image description here

    谢谢你的时间!

    1 回复  |  直到 8 年前
        1
  •  1
  •   eyllanesc    8 年前

    aboutToShow 在更新几何体之前发出,以便稍后覆盖更改。解决方案是在显示后立即更改位置,为此,我们可以使用 QTimer 时间很短。

    示例:

    #include <QApplication>
    #include <QMainWindow>
    #include <QMenuBar>
    #include <QTimer>
    
    class CenterMenu: public QMenu{
        Q_OBJECT
    public:
        CenterMenu(QWidget *parent = Q_NULLPTR):QMenu{parent}{
            connect(this, &CenterMenu::aboutToShow, this, &CenterMenu::centerMenu);
        }
        CenterMenu(const QString &title, QWidget *parent = Q_NULLPTR): QMenu{title, parent}{
            connect(this, &CenterMenu::aboutToShow, this, &CenterMenu::centerMenu);
        }
    private slots:
        void centerMenu(){
            QTimer::singleShot(0, [this](){
                move(pos() + QPoint(0, -height()/2));
            });
        }
    };
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        QMainWindow w;
    
        auto fileMenu = new QMenu("Menu1");
        w.menuBar()->addMenu(fileMenu);
        fileMenu->addAction("action1");
        fileMenu->addAction("action2");
        auto children_menu = new CenterMenu("children menu");
        children_menu->addAction("action1");
        children_menu->addAction("action2");
        children_menu->addAction("action3");
        children_menu->addAction("action4");
        children_menu->addAction("action5");
        children_menu->addAction("action6");
        fileMenu->addMenu(children_menu);
        w.show();
        return a.exec();
    }
    
    #include "main.moc"
    
    推荐文章