saga
saga

Reputation: 2113

Using a qml type as a QWindow in C++ code

I've created a MainWindow : public QMainWindow and a qtquick ui file (for a toolbox) in qtcreator. I want the toolbox to appear as a floating subwindow in mainwindow. I'm trying to use QMdiArea for that. A tutorial I've seen says that I need to add a window to the QMdiArea like this:

mdi->addSubWindow(win);

where win is a QWidget. How do I use the toolbox created with qml in my C++ code?

Upvotes: 1

Views: 693

Answers (2)

You can use without QMdiArea

int main(int argc, char *argv[])

{
    QApplication a(argc, argv);
    MainWindow w;
    QQuickWidget *toolbar = new QQuickWidget(QUrl("qrc:/main.qml"));
    toolbar->setResizeMode(QQuickWidget::SizeRootObjectToView);
    w.setCentralWidget(toolbar);
    w.show();
    return a.exec();
}

enter image description here

Upvotes: 0

eyllanesc
eyllanesc

Reputation: 244282

You can use QQuickWidget but remember that the root of the QML must be an Item or a class that inherits from the Item, it can not be Window or ApplicationWindow.

#include <QApplication>
#include <QMainWindow>
#include <QMdiArea>
#include <QQuickWidget>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QApplication app(argc, argv);
    QMainWindow w;
    QMdiArea *mdiarea = new QMdiArea;
    w.setCentralWidget(mdiarea);
    QQuickWidget *toolbar = new QQuickWidget(QUrl("qrc:/main.qml"));
    toolbar->setResizeMode(QQuickWidget::SizeRootObjectToView);
    mdiarea->addSubWindow(toolbar);
    w.show();
    return app.exec();
}

main.qml

import QtQuick 2.9
import QtQuick.Controls 2.4

Rectangle {
    visible: true
    width: 640
    height: 480
    color: "red"
    Button{
        text: "Stack Overflow"
        anchors.centerIn: parent
    }
}

enter image description here

Upvotes: 2

Related Questions