Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert QML view in a QWidget

I am a beginner in QML and try to insert a QML View in QWdiget but I don't understand why it doesn't work.

Here is a simple example of my qml file (this is not the real file):

import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
import QtQuick.Dialogs 1.2
import QtQuick.Layouts 1.2
import QtQml.Models 2.1

ObjectModel {
  id: itemModel
  Rectangle {
    color: "orange"
    anchors.fill: parent
  }
  Rectangle {
    color: "orange"
    anchors.fill: parent
  }
  Rectangle {
    color: "orange"
    anchors.fill: parent
  }
  
  ListView {
    id: my_list
    anchors.fill: parent
    model: itemModel
  }
}

And this is how I load it in my mainwindow:

QQuickView *view = new QQuickView();
QWidget *container = QWidget::createWindowContainer(view, this);
container->setMinimumSize(200, 200);
container->setFocusPolicy(Qt::TabFocus);
view->setSource(QUrl("main.qml"));
ui->dockWidget->setWidget(container);

How could I insert my view in a QWidget? At this time, I really need to use a QML view and because I need to use it in an already existing application, I can't just use a QML project.

Thanks a lot for your help and have a good day!

like image 282
Ed Nio Avatar asked Dec 18 '22 08:12

Ed Nio


2 Answers

There exist a special QQuickWidget, dedicated to that exact purpose.

QQuickWidget *view = new QQuickWidget;
view->setSource(QUrl::fromLocalFile("myqmlfile.qml"));
view->show();
like image 62
dtech Avatar answered Dec 28 '22 08:12

dtech


  1. QQmlApplicationEngine *m_engine in MainWindow.h
  2. in MainWindows.cpp set :
m_engine->addImportPath("qrc:/qml/imports");
m_engine->load(QUrl(QStringLiteral("qrc:/qml/main.qml")));
 // m_engine->rootContext()->setContextProperty("mainWindows", this);
qDebug() << "Ok engine created";`
`QWindow *qmlWindow = qobject_cast<QWindow*>(m_engine->rootObjects().at(0));
QWidget *container = QWidget::createWindowContainer(qmlWindow, this);
container->setMinimumSize(200, 200);
container->setMaximumSize(1200, 900);
ui->verticalLayout->addWidget(container);`

like image 44
Didier Restrepo Avatar answered Dec 28 '22 06:12

Didier Restrepo