Search code examples
qtqt5qtstylesheets

QMenuBar align QAction to center


I force set the QMenuBar's width to 40 by the setting minmumsize to 40.
Is there a way to set those Actions to center instead of on the top?
top-padding seems not working for me.

enter image description here


Solution

  • If I understood your question correctly, you could customize the QMenuBar using something like this:

    main.cpp

    #include "mainwindow.h"
    #include <QApplication>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        a.setStyleSheet("QMenuBar { min-width: 80px; min-height: 80px; } ");
        MainWindow w;
        w.show();
        return a.exec();
    }
    

    mainwindow.cpp

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    
    MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent)
        , ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
    
        QMenu *menu_a = menuBar()->addMenu(tr("&AAA"));
        menu_a->addAction("AAA");
        QMenu *menu_b = menuBar()->addMenu(tr("&BBB"));
        menu_b->addAction("BBB");
        QMenu *menu_c = menuBar()->addMenu(tr("&CCC"));
        menu_c->addAction("CCC");
    
        QWidget *central = new QWidget;
        setCentralWidget(central);
    }
    
    MainWindow::~MainWindow()
    {
        delete ui;
    }
    

    With this code you will get the following menu:

    enter image description here

    It's possible to customize the items too:

    QMenuBar::item { padding-top: 40px; }