qtqmainwindowqtoolbarqmenubar

How to put an icon to the left side of a QMenuBar and a QToolBar?


I need to put an icon at the top left side of QMainWindow. There is a toolbar and a menu bar to the left side, and a toolbar below, similar to this illustration:

illustration

How can I achieve this?


Solution

  • This answer is based on my answer on: how to add a header to a QMainWindow before the Menu Bar section?. I will only be modifying it based on your specific use case.

    You could make a normal widget that looks like the one you need as a header, simply by using layouts:

    Then use the result as a QMainWindow::menuWidget.

    The toolbar on the left can be added as usual.

    Minimal example:

    #include <QApplication>
    #include <QMainWindow>
    #include <QHBoxLayout>
    #include <QVBoxLayout>
    #include <QMenuBar>
    #include <QMenu>
    #include <QToolBar>
    #include <QLabel>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
    
        QMainWindow mainWindow;
    
        QWidget headerWidget;
        QHBoxLayout headerLayout(&headerWidget);
    
        headerWidget.setStyleSheet("background: darkgreen;");
    
        QLabel label;
        label.setPixmap(QPixmap(":/Resources/Images/icon.png"));
        label.setFixedSize(label.pixmap().size());
    
        headerLayout.addWidget(&label);
    
        QWidget menuContainerWidget;
        QVBoxLayout vboxLayout(&menuContainerWidget);
    
        headerLayout.addWidget(&menuContainerWidget);
    
        QMenuBar menubar;
        QToolBar toolBar;
        menubar.setStyleSheet("background: darkblue;");
        toolBar.setStyleSheet("background: darkblue;");
    
        vboxLayout.addWidget(&menubar);
        vboxLayout.addWidget(&toolBar);
    
        QMenu menu("menu");
        menubar.addMenu(&menu);
    
        mainWindow.setMenuWidget(&headerWidget);
    
        QWidget centralWidget;
        centralWidget.setStyleSheet("background: white;");
    
        mainWindow.setCentralWidget(&centralWidget);
    
        QToolBar leftToolBar;
        leftToolBar.setMinimumWidth(100);
    
        mainWindow.addToolBar(Qt::LeftToolBarArea, &leftToolBar);
    
        mainWindow.show();
    
        return a.exec();
    }
    

    Result:

    QMainWindow with a custom header widget, QLabel on the left, QMenbBar and QToolBar on the right