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

Accessing Q_PROPERTY property from stylesheet seems not work...



  • Hi everyone,
    i m trying to assign a css style to a QPushButton, everything goes fine when i define property with setProperty method, for example:

    QPushButton * myPB = new QPushButton;
    myPB->setProperty("propState","unset");
    

    then in css i have:

    QPushButton[propState="unset"] {
        border-radius: 20px;
        background: qradialgradient(
            cx: 0.3, cy: -0.4, fx: 0.3, fy: -0.4,
            radius: 1.1, stop: 0 #d9d9d9, stop: 1 #949494
            );
    

    this works perfectly. Then i wanted to use Q_PROPERTY, so i subclassed QPushButton, and added a property this way:

    /* header.h */
    class customPushButton : public QPushButton
    {
      Q_OBJECT
      Q_ENUMS(PBSTATE)
      Q_PROPERTY(PBSTATE propState READ getPState WRITE setPState NOTIFY PStateChanged)
    
    public:
      explicit customPushButton(QWidget *parent);
      ~customPushButton();
      enum PBSTATE {
        passed,
        failed,
        unset
      };
    
      void setPState(PBSTATE propState) {
        state = propState;
        emit PStateChanged(propState);
      }
      PBSTATE getPState() const {return state;}
    
    signals:
      void PStateChanged(PBSTATE);
    
    private:
      PBSTATE state;
    };
    

    then in file custom.cpp:

    customPushButton::customPushButton(QWidget * parent) {
    
     this->setParent(parent);
     ...
     this->setPState(PBSTATE::unset);
    }
    

    then i declared an instance of customPushButton in my main class, and after i applyedand stylesheet. In css i have:

    QPushButton[propState="unset"] {
        border-radius: 20px;
        background: qradialgradient(
            cx: 0.3, cy: -0.4, fx: 0.3, fy: -0.4,
            radius: 1.1, stop: 0 #d9d9d9, stop: 1 #949494
            );
    

    this won t work, seems css has difficuty to recognize "propState" as property... someone can tell me if i m doing things correctly?

    Thanks
    Emanuele Peruzzi



  • Your property is an enum, not a string, the value of QVariant::toString() would never be "unset". You should only be able to use number in that case, like

    QPushButton[propState="2"]
    


  • @Bonnie Thanks, works perfectly.


Log in to reply