How to access variables that are defined in a separate QML file?

71 Views Asked by At

I'm unable to access variables in a separate file.

Down below is part of my code:

// Style.qml

import QtQuick

QtObject {
    property int mainWindowWidth: 1024
    property int mainWindowHeight: 768
}

// Main.qml

import QtQuick
import QtQuick.Window

Window {
    id: root
    width: Style.mainWindowWidth
    height: Style.mainWindowHeight
    minimumWidth: width
    minimumHeight: height
    maximumWidth: width
    maximumHeight: height
    visible: true
    title: "Sampletext"
}

It compiles fine but when I run it, I get an error saying:

Unable to assign [undefined] to int where the line width: Style.mainWindowWidth is located.

How do I fix this?

1

There are 1 best solutions below

0
Mohsen Kondori On

You should create an instance of the Style component or define Style as a singleton component. Definition of Style as singleton is as follows:

Style.qml
pragma Singleton

import QtQuick

QtObject {
    property int mainWindowWidth: 1024
    property int mainWindowHeight: 768
}
CMakeLists.txt:
set_source_files_properties(
    Style.qml
    PROPERTIES QT_QML_SINGLETON_TYPE True
)

qt6_add_qml_module(appExample
    URI appExample
    VERSION 1.0
    QML_FILES
        Main.qml
        Style.qml
)
Main.qml
import QtQuick
import QtQuick.Window

import appExample

Window {
    id: root
    width: Style.mainWindowWidth
    height: Style.mainWindowHeight
    minimumWidth: width
    minimumHeight: height
    maximumWidth: width
    maximumHeight: height
    visible: true
    title: "Sample Text"
}