The Property System¶
An overview of Qt’s property system.
Qt provides a sophisticated property system similar to the ones supplied by some compiler vendors. However, as a compiler- and platform-independent library, Qt does not rely on non-standard compiler features like
__property
or[property]
. The Qt solution works with any standard C++ compiler on every platform Qt supports. It is based on the Meta-Object System that also provides inter-object communication via signals and slots .
Requirements for Declaring Properties¶
To declare a property, use the
Q_PROPERTY()
macro in a class that inheritsQObject
.Q_PROPERTY(type name (READ getFunction [WRITE setFunction] | MEMBER memberName [(READ getFunction | WRITE setFunction)]) [RESET resetFunction] [NOTIFY notifySignal] [REVISION int] [DESIGNABLE bool] [SCRIPTABLE bool] [STORED bool] [USER bool] [CONSTANT] [FINAL] [REQUIRED])Here are some typical examples of property declarations taken from class
QWidget
.Q_PROPERTY(bool focus READ hasFocus) Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled) Q_PROPERTY(QCursor cursor READ cursor WRITE setCursor RESET unsetCursor)Here is an example showing how to export member variables as Qt properties using the
MEMBER
keyword. Note that aNOTIFY
signal must be specified to allow QML property bindings.Q_PROPERTY(QColor color MEMBER m_color NOTIFY colorChanged) Q_PROPERTY(qreal spacing MEMBER m_spacing NOTIFY spacingChanged) Q_PROPERTY(QString text MEMBER m_text NOTIFY textChanged) ... signals: void colorChanged(); void spacingChanged(); void textChanged(const QString &newText); private: QColor m_color; qreal m_spacing; QString m_text;A property behaves like a class data member, but it has additional features accessible through the Meta-Object System .
A
READ
accessor function is required if noMEMBER
variable was specified. It is for reading the property value. Ideally, a const function is used for this purpose, and it must return either the property’s type or a const reference to that type. e.g.,focus
is a read-only property withREAD
function,hasFocus()
.A
WRITE
accessor function is optional. It is for setting the property value. It must return void and must take exactly one argument, either of the property’s type or a pointer or reference to that type. e.g.,enabled
has theWRITE
functionsetEnabled()
. Read-only properties do not needWRITE
functions. e.g.,focus
has noWRITE
function.A
MEMBER
variable association is required if noREAD
accessor function is specified. This makes the given member variable readable and writable without the need of creatingREAD
andWRITE
accessor functions. It’s still possible to useREAD
orWRITE
accessor functions in addition toMEMBER
variable association (but not both), if you need to control the variable access.A
RESET
function is optional. It is for setting the property back to its context specific default value. e.g.,cursor
has the typicalREAD
andWRITE
functions,cursor()
andsetCursor()
, and it also has aRESET
function,unsetCursor()
, since no call tosetCursor()
can mean reset to the context specific cursor. TheRESET
function must return void and take no parameters.A
NOTIFY
signal is optional. If defined, it should specify one existing signal in that class that is emitted whenever the value of the property changes.NOTIFY
signals forMEMBER
variables must take zero or one parameter, which must be of the same type as the property. The parameter will take the new value of the property. TheNOTIFY
signal should only be emitted when the property has really been changed, to avoid bindings being unnecessarily re-evaluated in QML, for example. Qt emits automatically that signal when needed for MEMBER properties that do not have an explicit setter.A
REVISION
number is optional. If included, it defines the property and its notifier signal to be used in a particular revision of the API (usually for exposure to QML). If not included, it defaults to 0.The
DESIGNABLE
attribute indicates whether the property should be visible in the property editor of GUI design tool (e.g., Qt Designer). Most properties areDESIGNABLE
(default true). Instead of true or false, you can specify a boolean member function.The
SCRIPTABLE
attribute indicates whether this property should be accessible by a scripting engine (default true). Instead of true or false, you can specify a boolean member function.The
STORED
attribute indicates whether the property should be thought of as existing on its own or as depending on other values. It also indicates whether the property value must be saved when storing the object’s state. Most properties areSTORED
(default true), but e.g.,minimumWidth()
hasSTORED
false, because its value is just taken from the width component of propertyminimumSize()
, which is aQSize
.The
USER
attribute indicates whether the property is designated as the user-facing or user-editable property for the class. Normally, there is only oneUSER
property per class (default false). e.g.,checked
is the user editable property for (checkable) buttons. Note thatQItemDelegate
gets and sets a widget’sUSER
property.The presence of the
CONSTANT
attribute indicates that the property value is constant. For a given object instance, the READ method of a constant property must return the same value every time it is called. This constant value may be different for different instances of the object. A constant property cannot have a WRITE method or a NOTIFY signal.The presence of the
FINAL
attribute indicates that the property will not be overridden by a derived class. This can be used for performance optimizations in some cases, but is not enforced by moc. Care must be taken never to override aFINAL
property.The presence of the
REQUIRED
attribute indicates that the property should be set by a user of the class. This is not enforced by moc, and is mostly useful for classes exposed to QML. In QML, classes with REQUIRED properties cannot be instantiated unless all REQUIRED properties have been set.The
READ
,WRITE
, andRESET
functions can be inherited. They can also be virtual. When they are inherited in classes where multiple inheritance is used, they must come from the first inherited class.The property type can be any type supported by
QVariant
, or it can be a user-defined type. In this example, classQDate
is considered to be a user-defined type.Q_PROPERTY(QDate date READ getDate WRITE setDate)Because
QDate
is user-defined, you must include the<QDate>
header file with the property declaration.For historical reasons,
QMap
andQList
as property types are synonym ofQVariantMap
andQVariantList
.
Reading and Writing Properties with the Meta-Object System¶
A property can be read and written using the generic functions
property()
andsetProperty()
, without knowing anything about the owning class except the property’s name. In the code snippet below, the call tosetDown()
and the call tosetProperty()
both set property “down”.QPushButton *button = new QPushButton; QObject *object = button; button->setDown(true); object->setProperty("down", true);Accessing a property through its
WRITE
accessor is the better of the two, because it is faster and gives better diagnostics at compile time, but setting the property this way requires that you know about the class at compile time. Accessing properties by name lets you access classes you don’t know about at compile time. You can discover a class’s properties at run time by querying itsQObject
,QMetaObject
, andQMetaProperties
.QObject *object = ... const QMetaObject *metaobject = object->metaObject(); int count = metaobject->propertyCount(); for (int i=0; i<count; ++i) { QMetaProperty metaproperty = metaobject->property(i); const char *name = metaproperty.name(); QVariant value = object->property(name); ... }In the above snippet,
property()
is used to getmetadata
about each property defined in some unknown class. The property name is fetched from the metadata and passed toproperty()
to get thevalue
of the property in the currentobject
.
A Simple Example¶
Suppose we have a class MyClass, which is derived from
QObject
and which uses theQ_OBJECT
macro in its private section. We want to declare a property in MyClass to keep track of a priority value. The name of the property will be priority , and its type will be an enumeration type named Priority , which is defined in MyClass.We declare the property with the
Q_PROPERTY()
macro in the private section of the class. The requiredREAD
function is namedpriority
, and we include aWRITE
function namedsetPriority
. The enumeration type must be registered with the Meta-Object System using theQ_ENUM()
macro. Registering an enumeration type makes the enumerator names available for use in calls tosetProperty()
. We must also provide our own declarations for theREAD
andWRITE
functions. The declaration of MyClass then might look like this:class MyClass : public QObject { Q_OBJECT Q_PROPERTY(Priority priority READ priority WRITE setPriority NOTIFY priorityChanged) public: MyClass(QObject *parent = 0); ~MyClass(); enum Priority { High, Low, VeryHigh, VeryLow }; Q_ENUM(Priority) void setPriority(Priority priority) { m_priority = priority; emit priorityChanged(priority); } Priority priority() const { return m_priority; } signals: void priorityChanged(Priority); private: Priority m_priority; };The
READ
function is const and returns the property type. TheWRITE
function returns void and has exactly one parameter of the property type. The meta-object compiler enforces these requirements.Given a pointer to an instance of MyClass or a pointer to a
QObject
that is an instance of MyClass, we have two ways to set its priority property:MyClass *myinstance = new MyClass; QObject *object = myinstance; myinstance->setPriority(MyClass::VeryHigh); object->setProperty("priority", "VeryHigh");In the example, the enumeration type that is the property type is declared in MyClass and registered with the Meta-Object System using the
Q_ENUM()
macro. This makes the enumeration values available as strings for use as in the call tosetProperty()
. Had the enumeration type been declared in another class, its fully qualified name (i.e., OtherClass::Priority) would be required, and that other class would also have to inheritQObject
and register the enumeration type there using theQ_ENUM()
macro.A similar macro,
Q_FLAG()
, is also available. LikeQ_ENUM()
, it registers an enumeration type, but it marks the type as being a set of flags , i.e. values that can be OR’d together. An I/O class might have enumeration valuesRead
andWrite
and thensetProperty()
could acceptRead | Write
.Q_FLAG()
should be used to register this enumeration type.
Dynamic Properties¶
setProperty()
can also be used to add new properties to an instance of a class at runtime. When it is called with a name and a value, if a property with the given name exists in theQObject
, and if the given value is compatible with the property’s type, the value is stored in the property, and true is returned. If the value is not compatible with the property’s type, the property is not changed, and false is returned. But if the property with the given name doesn’t exist in theQObject
(i.e., if it wasn’t declared withQ_PROPERTY()
), a new property with the given name and value is automatically added to theQObject
, but false is still returned. This means that a return of false can’t be used to determine whether a particular property was actually set, unless you know in advance that the property already exists in theQObject
.Note that dynamic properties are added on a per instance basis, i.e., they are added to
QObject
, notQMetaObject
. A property can be removed from an instance by passing the property name and an invalidQVariant
value tosetProperty()
. The default constructor forQVariant
constructs an invalidQVariant
.Dynamic properties can be queried with
property()
, just like properties declared at compile time withQ_PROPERTY()
.
Properties and Custom Types¶
Custom types used by properties need to be registered using the
Q_DECLARE_METATYPE()
macro so that their values can be stored inQVariant
objects. This makes them suitable for use with both static properties declared using theQ_PROPERTY()
macro in class definitions and dynamic properties created at run-time.
Adding Additional Information to a Class¶
Connected to the property system is an additional macro,
Q_CLASSINFO()
, that can be used to attach additional name –value pairs to a class’s meta-object, for example:Q_CLASSINFO("Version", "3.0.0")Like other meta-data, class information is accessible at run-time through the meta-object; see
classInfo()
for details.See also
Meta-Object System Signals and Slots
Q_DECLARE_METATYPE()
QMetaType
QVariant
© 2022 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.