1
votes

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

  • limit the amount of code in the main files (hide all styling stuff in styling files, unlike in the Style Singleton approach)
  • not have to define every single type of item I'm going to use (unlike in the Custom Component approach)
  • possibly be able to mix and match different pre-defined styles in a single item.

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:

  • I'd like for the styling to be applied statically, once and for all
  • if I start using this all over the place, won't I see artifacts when objects get created, and slow down my interface?

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:

  • well, it doesn't work :-) (no warnings though, qml simply doesn't load)
  • and I'm sort of back to having to define every single type of items I'm going to use.

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

1
I think you are going to have some difficulties doing it this way. For example, how would you style things as highlighted buttons? - Amfasis

1 Answers

1
votes

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"
    }
}