Important: Please read the Qt Code of Conduct -

[SOLVED] Set dynamic property by stylesheet?

  • Hello,

    I would like to set a dynamic property (one that hasn't been declared by Q_PROPERTY but added at runtime) by stylesheet.

    svg->setProperty("color", 123);
    svg->setStyleSheet("qproperty-color: 456;");
    cout << "PROP: " << svg->property("color").toInt() << endl;

    Unfortunately, the output is 123, so it has not been set by the stylesheet.

    It works however if the property is declared by Q_PROPERTY first.

    Is this by design? Is there a way to set dynamically added properties by stylesheet?

    Thank you very much!

  • To proper use dynamamic property you must first of all use Q_PROPERTY. Second, you must have appropriate getter and setter.
    Third, property and styleSheet is a different thinkgs.
    cout << "PROP: " << svg->property("color").toInt() << endl; //What are you expected here??? according your code you must have here 123.

    I think you must write something like bellow

    QString color = svg->getProperty("color", 123);
    svg->setStyleSheet("qproperty-color: "+color+";");
    cout << "PROP: " << svg->property("color").toInt() << endl;

  • I don't think that Q_PROPERTY is necessary to use a property.

    QObject::setProperty() can also be used to add new properties to an instance of a class at runtime. [...] But if the property with the given name doesn't exist in the QObject (i.e., if it wasn't declared with Q_PROPERTY()), a new property with the given name and value is automatically added to the QObject [...]

    I am expecting an output of 456 because I have changed the previously added property "color" by stylesheet to 456 with "qproperty-color: 456;".

  • Hi @qtacc32

    You can have a look at Dynamic Properties and Stylesheets

  • Hi,
    thanks but this just isn't what I want to do.

    I want to add a new property at runtime with setProperty().
    Then I want to change that property value via stylesheet.

  • Lifetime Qt Champion


    AFAIK, you can't for dynamic properties. Setting a property from sa tyle sheet requires that property to be designable Q_PROPERTY (explained here)

  • Okay, thank you. I missed "designable", probably because I didn't know what it means.

  • Lifetime Qt Champion

    You're welcome !

    You have more information about "designable" here