Home > Net >  Unable to assign [undefined] to QColor when including QtObject as styling file
Unable to assign [undefined] to QColor when including QtObject as styling file

Time:10-19

I am trying to add set of custom properties to be included by several labels on my QML. The idea is to make a style, but I keep getting these errors:

qrc:/TestPage.qml:18:9: Unable to assign [undefined] to QColor
qrc:/TestPage.qml:17:9: Unable to assign [undefined] to double
qrc:/TestPage.qml:16:9: Unable to assign [undefined] to QString

I was following the thread below but did not work for me.

Unable to assign [undefined] to QColor

Here is my label:

import "Theme"

Label
{
    font.family: Theme.tfont
    font.pointSize: Theme.tpointSize
    color: Theme.tcolor
    text: "text"
}

and here is my Theme.qml file:

pragma Singleton

import QtQuick

QtObject
{
    readonly property string tfont: {return "Calibri"}
    readonly property real tpointSize: {return 28}
    readonly property string tcolor: {return "black"}
}

any ideas why it won't resolve the property?

CodePudding user response:

I made the following changes to your app:

  • Declare qmldir
  • Don't need import "Theme"
  • Refactor AppLabel
  • Don't use return when declaring properties declaratively
import QtQuick
import QtQuick.Controls
Page {
    AppLabel { text: "text" }
}

//AppLabel.qml
import QtQuick
import QtQuick.Controls
Label {
    font.family: Theme.tfont
    font.pointSize: Theme.tpointSize
    color: Theme.tcolor
}

//qmldir
singleton Theme 1.0 Theme.qml

//Theme.qml
pragma Singleton
import QtQuick
QtObject
{
    readonly property string tfont: "Calibri"
    readonly property real tpointSize: 28
    readonly property string tcolor: "black"
}

You can Try it Online!

CodePudding user response:

Check that example it uses a Style.qml to define a global theme. As Stephen Quan already said you should create a qmldir to define the singleton.

The important part here is to also include the qmldir and the Theme.qml in your CMakeLists.txt or pro.

CMakeLists.txt

...
qt_add_qml_module(appuntitled
    URI untitled
    VERSION 1.0
    QML_FILES
        main.qml
        qmldir
        Theme.qml
)
...

qmldir

singleton Theme 1.0 Theme.qml

Theme.qml

pragma Singleton

import QtQuick

QtObject {
    readonly property string tfont: "Calibri"
    readonly property real tpointSize: 28
    readonly property string tcolor: "black"
}

main.qml

import QtQuick
import QtQuick.Controls

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

    Label {
        font.family: Theme.tfont
        font.pointSize: Theme.tpointSize
        color: Theme.tcolor
        text: "text"
    }
}
  • Related