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

How do I access a Q_PROPERTY of a class from another class?



  • I have a Q_PROPERTY and I want to access the current state of that property from another class. Ie, this other class will make decisions based on the state. Here is the Q_PROPERTY:

    Q_PROPERTY(bool isCompact READ isCompact WRITE setIsCompact NOTIFY isCompactChanged)
    

    so what's the standard way of doing this? Do I need a getter for isCompact or do I create a new variable in the new class which will be updated whenever isCompactChanged or something else?


  • Moderators

    this other class will make decisions based on the state

    Based on this alone, I'd say the proper way is to connect to isCompactChanged() in your other class. This way you don't even need to store a pointer to your class containing the property - you get a clear separation of data and responsibilities. It's easy to maintain and refactor such code.

    But if your use case is different, there is nothing wrong with calling the isCompact() method (getter) or even in some cases it's perfectly fine to call object->property("isCompact").toBool(). All depends on the gory details, as usual ;-)


  • Moderators

    this other class will make decisions based on the state

    Based on this alone, I'd say the proper way is to connect to isCompactChanged() in your other class. This way you don't even need to store a pointer to your class containing the property - you get a clear separation of data and responsibilities. It's easy to maintain and refactor such code.

    But if your use case is different, there is nothing wrong with calling the isCompact() method (getter) or even in some cases it's perfectly fine to call object->property("isCompact").toBool(). All depends on the gory details, as usual ;-)



  • @sierdzio "...it's perfectly fine to call object->property("isCompact").toBool()"

    Interesting, what would this object be exactly? The Q_PROPERTY exists in a header GuidanceBarPresenter.h so would that be my object?


  • Moderators

    @RobM said in How do I access a Q_PROPERTY of a class from another class?:

    @sierdzio "...it's perfectly fine to call object->property("isCompact").toBool()"

    Interesting, what would this object be exactly? The Q_PROPERTY exists in a header GuidanceBarPresenter.h so would that be my object?

    Yes, the object containing the property.


Log in to reply