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

80 Views Asked by At

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?

1

There are 1 best solutions below

0
A.R.M On BEST ANSWER

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:

  • A container widget with a QHBoxLayout.
  • Add a QLabel to show the logo in that layout.
  • Add another widget to the QHBoxLayout with a QVBoxLayout.
  • Add the QMenuBar and QToolBar to this second container widget using QLayout::addWidget.

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