Zer0
Zer0

Reputation: 1166

How to assign QML file to MainWindow/Application

SITUATION

I have my main.cpp here

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickView>
#include <QQmlContext>

#include "root.h"


int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQuickView view;
    testApp::Root data;

    view.rootContext()->setContextProperty("dataContext", &data);
    view.setSource(QUrl::fromLocalFile("main.qml"));
    view.show();

    return app.exec();
}

and my main.qml here

import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World!!!")
}

PROBELM

whenever i start my app, it does not assign the values from main.qml to my main window.

for example: the properties width, height in main.qml have the values 640, 480. But whenever i start the app, my window is much smaller(and yes i have tried to give them different values)

QUESTION

how to say the program: he should use main.qml for my main window.

Upvotes: 1

Views: 1444

Answers (1)

eyllanesc
eyllanesc

Reputation: 244301

If you are using QQuickView then the root has to be a QQuickItem as Item, Rectangle, etc. since QQuickView is a window.

If instead you want to root Window or ApplicationWindow then you must use QQmlApplicationEngine.

In your case there are 2 windows: One the QQuickView and the other the Window.

Considering the above you have the following 2 options:

  1. QQuickView
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQuickView view;
    testApp::Root data;
    view.view.setResizeMode(QQuickView::SizeRootObjectToView);

    view.rootContext()->setContextProperty("dataContext", &data);
    view.setSource(QUrl::fromLocalFile("main.qml"));
    view.setTitle("Hello World!!!")
    view.show();

    return app.exec();
}
import QtQuick 2.12
import QtQuick.Window 2.12

Item {
    width: 640
    height: 480
}
  1. QQmlApplicationEngine
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    testApp::Root data;

    engine.rootContext()->setContextProperty("dataContext", &data);
    engine.load(QUrl::fromLocalFile("main.qml"));

    return app.exec();
}
import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World!!!")
}

Upvotes: 2

Related Questions