Button backgound non-existent property!
-
Using
QtQuick.Controls 2.0
I want to change the backgound color ofButton
but Qt says to meCannot assign to non-existent property "color"
Why I can't use
background.color: "red"
while I can usebutton.background.color = "red"
?!Button { id: button x: 220 y: 281 width: 200 height: 40 text: qsTr("Button") // ERROR!!! //background.color: "red" } Component.onCompleted: { // WORKS! button.background.color = "red" }
-
Background is not an attached property, so setting up bindings like
object.property: something
will not work.You can either use Binding QML type, or define the background yourself:
Button { background: Rectangle { color: "red" } }
-
Sorry @sierdzio but I asked this question because I want to change
Button
background color on runtime like thisButton { id: button x: 220 y: 281 width: 200 height: 40 text: qsTr("Button") } Component.onCompleted: { // WORKS! // button.background.color = "red" // WRONG background = Rectangle { color: "red" } }
-
It's better to use declarative approach and do it via binding, but yes, changing it via JavaScript in a function is possible, too.
Why Qt Creator did not auto-complete it? Well, probably it's engine does not understand it well enough. What you did in Component.onCompleted is perfectly legal, though. Don't worry about Qt Creator :-)
BTW. Also, consider using Controls' styles: link.
-
@tansgumus said in Button backgound non-existent property!:
Component.onCompleted: { // WORKS! // button.background.color = "red" // WRONG background = Rectangle { color: "red" } }
Because Component.onCompleted is a javascript function and you can use only js syntax inside it. Rectangle { color: "red" } is QML specific syntax, js doesn't understand it. You can create a component dynamically (see the QML docs) by giving the component as a string to Qt.createQmlObject().
If you use button.background.color = "red" in Component.onCompleted it retains all other properties of the backround; I have found it to be a convenient way to change only one or two properties without messing others. Using other approaches, i.e. defining the whole component either dynamically or declaratively, overwrites everything which may or may not be desirable.