user2366975
user2366975

Reputation: 4720

Embedding QQuickWidget map inside QWidget not working

I have a weird problem regarding embedding the standalone Qt example "mapviewer" inside a QtWidgets desktop app for the sake of displaying a tiled map. Standalone it works, e.g. loading a map. Embedded inside a QWidget with the recommended way of using QQuickWidget, nothing is working as expected.

Here is the source:

#include "mapwidget.h"    
#include <QtQuickWidgets/QQuickWidget>    
#include <QLabel>
#include <QVBoxLayout>    
#include <QQmlApplicationEngine>
MapWidget::MapWidget(QWidget *parent)
    : QWidget(parent)
{
    this->setLayout(new QVBoxLayout);
    this->layout()->addWidget(new QLabel("label"));

    view_ = new QQuickWidget(nullptr);
    view_->setWindowTitle("QQuickWidget");
//    view_->engine()->addImportPath(QStringLiteral(":/imports"));
    QUrl url(QStringLiteral("qrc:///mapviewer.qml"));
    view_->setSource(url);

    // Show or embedd the widget, try it out
    view_->show();
    // this->layout()->addWidget(view_);

    QFile f(":/mapviewer.qml");
    if ( f.open( QIODevice::ReadOnly )){}
    Q_ASSERT(f.isOpen()); // OKAY so the qml file is found
    f.close();
}

header:

#ifndef MAPWIDGET_H
#define MAPWIDGET_H

#include <QWidget>
class QQuickWidget;
class MapWidget : public QWidget
{
    Q_OBJECT
    QQuickWidget *view_ = nullptr;
public:
    explicit MapWidget(QWidget *parent = nullptr);
    ~MapWidget() = default;
};

#endif // MAPWIDGET_H

I have no idea what is so complicated here. I am very familiar with QtWidgets but new to qml, so maybe I lack something quite obvious.

enter image description here

Upvotes: 2

Views: 2677

Answers (1)

Pavan Chandaka
Pavan Chandaka

Reputation: 12821

The QQuickWidget is not a good thing in your case. This is a good one, if your user interface is Qt Quick and want to show it.

But here, you are embedding QML in C++ Qt widgets. For this scenario QDeclarativeView is a good class.

Look for below statement in documentation link.

QDeclarativeView is a QGraphicsView subclass provided as a convenience for displaying QML files, and connecting between QML and C++ Qt objects.

http://doc.qt.io/qt-4.8/qdeclarativeview.html#details

try something like this:

QDeclarativeView *qmlView = new QDeclarativeView;
qmlView->setSource(QUrl::fromLocalFile("qrc:///mapviewer.qml"));

this->layout()->addWidget(qmlView);

Also in the above link, below the highlighted statement, You can see a good description of when to use QML and drawbacks of embedding more QMLs in widgets etc...

In latest versions of Qt, the QDeclarativeView is deprecated and the recommended replacement is QQuickView.

Embedding QQuickView in QWidget:

Use createWindowContainer to get a widget for QQuickView.

QQuickView *qmlView = new QQuickView();
QWidget *container = QWidget::createWindowContainer(qmlView, this);
qmlView->setSource(QUrl("qrc:///mapviewer.qml"));
this->layout()->addWidget(qmlView);

Upvotes: 3

Related Questions