main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QScreen>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
QQmlContext* context = engine.rootContext();
QScreen* screen = QGuiApplication::primaryScreen();
QRect rect = screen->virtualGeometry();
context->setContextProperty("SCREEN_WIDTH",800);
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
main.qml
import QtQuick 2.14
import QtQuick.Controls 2.14
ApplicationWindow {
visible: true
width: SCREEN_WIDTH
height: 480
title: qsTr("Hello World")
MyRectangle{
Component.onCompleted: {
attr.testValue = 100
console.log(attr.testValue)
}
}
QtObject{
}
}
MyRectangle.qml
import QtQuick 2.0
import QtQuick.Controls 2.12
Rectangle{
width: 200
height: 100
color: "black"
property alias attr: attributes
QtObject{
id: attributes
property int testValue: 0
}
Component.onCompleted: {
}
}