Alex44
Alex44

Reputation: 3855

Qt5: Derive QQuickWidget to get a widget

I try to embed this qml definition:

import QtQuick 2.0

Rectangle {
    id: mqldefinition
    color: "green"
    width: 100
    height: 100

    Text {
        id: text
        text: "This is a text!"
        font.pointSize: 14
        anchors.centerIn: parent
    }
}

within a Qt C++-widget:

qmlwidget.h

#include <QQuickWidget>

class QmlWidget
      : public QQuickWidget
{
    Q_OBJECT
public:
    explicit QmlWidget(QWidget *parent = nullptr);
};

qmlwidget.h

#include "qmlwidget.h"

QmlWidget::QmlWidget(QWidget *parent)
   : QQuickWidget(parent)
{
    resize(100,100);
    setSource(QUrl("qrc:/definition.qml"));
}

This widget shall be shown within the MainWindow as partly shown here:
mainwindow.cpp

#include "mainwindow.h"
#include "qmlwidget.h"

MainWindow::MainWindow(QWidget *parent)
   : QMainWindow(parent)
{
    auto qmlWidget = new QmlWidget(this);
    qmlWidget->move(0,0);
}

But it is not shown :(


I found this in SO:

QQuickWidget *view = new QQuickWidget;
view->setSource(QUrl::fromLocalFile("myqmlfile.qml"));
view->show();

but I would like to implement it as derived class :)

Upvotes: 2

Views: 781

Answers (1)

eyllanesc
eyllanesc

Reputation: 243907

One possible solution is to set the QmlWidget as centralWidget.

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    QmlWidget *qmlWidget = new QmlWidget;
    qmlWidget->setResizeMode(QQuickWidget::SizeRootObjectToView);
    setCentralWidget(qmlWidget);
}

enter image description here

Another approach is to use layouts to handle the size of the widget.

Upvotes: 2

Related Questions