qtqml

How to embed QML toolbar and menubar into QMainWindow


I am using QWT library to plot data. It seems that it is not possible to embed QWidget into QML Quick 2. So, I decided to create QMainWindow as my main window and create its toolbar and menubar using Quick Controls. How should I embed that qml toolbar and menubar into QMainWindow?


Solution

  • You should create QML ApplicationWindow with QML MenuBar and ToolBar

    main.qml

    ApplicationWindow {
        visible: false
        menuBar: MenuBar {
            Menu {
                title: "Edit"
                MenuItem {
                    text: "Cut"
                }
            }
        }
        toolBar: ToolBar {
            Row {
                anchors.fill: parent
                ToolButton {
                    iconSource: "1.png"
                }
            }
        }
    }
    

    main.cpp

    QApplication app(argc, argv);
    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
    

    Then get pointer to your ApplicationWindow

    QWindow *qmlWindow = qobject_cast<QWindow*>(engine.rootObjects().at(0));
    

    Create window container, by using QWidget::createWindowContainer

    QWidget *container = QWidget::createWindowContainer(qmlWindow);
    container->setMinimumSize(qmlWindow->size());
    

    And place container to the top of your widget

    QWidget *widget = new QWidget();
    QGridLayout *grid = new QGridLayout(widget);
    grid->addWidget(container,0,0);
    grid->addWidget(new QPushButton(widget),1,0);
    widget->show();