Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

error in qml type converting while qml styling



  • first , I found two post and want to try their skinnable idea as follows :

    https://stackoverflow.com/questions/36335481/dynamically-change-qml-theme-at-runtime/36399339#36399339

    https://stackoverflow.com/questions/23518071/qt-5-styling-dynamically-load-qml-files/25866188#25866188

    I almost copied their code , but failed and errors occurs:
    Item {
    id : base
    ...
    property AbstractStyle currentStyle : Style.createStyleObject(base, "qrc:/StyleA.qml");

    Text {
    x: 100
    y: 0
    font.pixelSize: currentStyle.textSize
    color: currentStyle.textColor
    text: "Hello World"
    }
    }
    while code running , it reports error showing "Unable to assign AbstractStyle_QMLTYPE_37 to AbstractStyle_QMLTYPE_0".



  • here is my code:
    // AbstractStyle.qml
    import QtQuick 2.0
    QtObject {
    property int textSize;
    property color textColor;
    }

    // StyleA.qml
    import QtQuick 2.0
    AbstractStyle {
    textSize : 20
    textColor : "red"
    }

    // StyleB.qml
    import QtQuick 2.0
    AbstractStyle {
    textSize : 50
    textColor : "green"
    }

    //componentCreation.js
    var component;
    var sprite;
    function createStyleObject(item, stylePath)
    {
    component = Qt.createComponent(stylePath);
    if( component.status == Component.Ready ){
    sprite = component.createObject(item);
    console.log("[!!!OK!!!]componentCreation.js:" + stylePath + " component ready");
    }
    else
    console.log("componentCreation.js:" + stylePath + " component not ready");
    if (sprite === null)
    console.log("componentCreation.js: error creating " + stylePath + " object");
    else
    return sprite;
    }

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

    QQuickView *view = new QQuickView;
    view->setResizeMode(QQuickView::SizeRootObjectToView);
    view->setSource(QUrl(QStringLiteral("qrc:///main.qml")));
    view->show();
    
    return app.exec();
    

    }

    //main.qml
    import "qrc:/styles/componentCreation.js" as Style
    Item {
    id : base
    ...
    property AbstractStyle currentStyle : Style.createStyleObject(base, "qrc:/StyleA.qml");

    Text {
    x: 100
    y: 0
    font.pixelSize: currentStyle.textSize
    color: currentStyle.textColor
    text: "Hello World"
    }
    }



  • well , after some help and tests , it comes to conclusion:

    this works in Qt 5.12.0 and above

    property AbstractStyle currentStyle : Style.createStyleObject(base, "qrc:/StyleA.qml");

    these two works in Qt 5.10.1 and above

    property QtObject currentStyle : Style.createStyleObject(base, "qrc:/StyleA.qml");
    property var currentStyle : Style.createStyleObject(base, "qrc:/StyleA.qml");


Log in to reply