Will59
Will59

Reputation: 1883

Trying to style Qt QML items by inserting child styling item

I'm trying different approaches to styling a QT's app QML items. My goal is to:

Maybe there is a clear strategy to get this, I just didn't read about it yet. And maybe it doesn't make any sense anyway :-)

I've been playing with the idea of defining different components, one for each style type I want to define. The idea is to: - define a component which is going to modify its parent - insert that component where I want to adopt that specific style

A first approach relies on some javascript calls:

MyStyle.qml:

Item {
  Component.onCompleted: {
    parent.color = "lightblue"
    parent.radius = 5
    parent.border.width = 3
    parent.border.color = "black"
  }
}

And in my main code:

    Rectangle {
      id: testRectangle
      anchors.fill: parent
      MyStyle {}
    }

This gives me the result I want, but it doesn't feel right:

So I tried this too:

MyRectangleStyle.qml:

Item {
  property Rectangle styleTarget
  styleTarget.color: "lightblue"
  styleTarget.radius: 5
  styleTarget.border.width: 3
  styleTarget.border.color: "black"
}

and in my main code:

    Rectangle {
      id: testRectangle
      anchors.fill: parent
      MyStyle {styleTarget: testRectangle}
    }

But:

So, is there a better way to achieve what I'm trying to do here? Thanks!

Upvotes: 1

Views: 287

Answers (1)

eyllanesc
eyllanesc

Reputation: 243945

Your second method does not work because your Component sets properties to an item that does not necessarily exist at the time of creating the Component, instead it sets the property when the styleTarget changes. On the other hand, it is not necessary for MyStyle to be an Item since it is not shown, instead use QtObject, and finally to generalize your method change property Item styleTarget toproperty Rectangle styleTarget:

QtObject {
    property Item styleTarget
    onStyleTargetChanged: {
        styleTarget.color = "lightblue"
        styleTarget.radius = 5
        styleTarget.border.width = 3
        styleTarget.border.color= "black"
    }
}

Upvotes: 1

Related Questions