1// Copyright (C) 2017 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
4\page qtqml-cppintegration-exposecppattributes.html
5\title Exposing Attributes of C++ Types to QML
6\brief Description of how to expose the attributes of a C++ type to QML
8QML can easily be extended with functionality defined in C++ code. Due to the
9tight integration of the QML engine with the \l{The Meta-Object System}{Qt
10meta-object system}, any functionality that is appropriately exposed by a
11QObject-derived class or a Q_GADGET type is accessible from QML code. This
12enables C++ data and functions to be accessible directly from QML, often with
13little or no modification.
15The QML engine has the ability to introspect QObject instances through the
16meta-object system. This means any QML code can access the following members of
17an instance of a QObject-derived class:
21\li Methods (providing they are public slots or flagged with Q_INVOKABLE)
25(Additionally, enums are available if they have been declared with Q_ENUM.
26See \l{qtqml-cppintegration-data.html}{Data Type Conversion Between QML and C++}
29In general, these are accessible from QML regardless of whether a
30QObject-derived class has been \l{Registering C++ types with the QML type
31system}{registered with the QML type system}. However, if a class is to be
32used in a way that requires the engine to access additional type information
33— for example, if the class itself is to be used as a method parameter or
34property, or if one of its enum types is to be used in this way — then the
35class may need to be registered. Registration is recommended for all types you
36use in QML, as only registered types can be analyzed at compile time.
38Registration is required for Q_GADGET types, as they don't derive from a known
39common base and can't be made available automatically. Without registration,
40their properties and methods are inaccessible.
42Also note that a number of the important concepts covered in this document are
43demonstrated in the \l{Writing QML Extensions with C++} tutorial.
45For more information about C++ and the different QML integration methods,
47\l {Overview - QML and C++ Integration} {C++ and QML integration overview} page.
49\section1 Data Type Handling and Ownership
51Any data that is transferred from C++ to QML, whether as a property value, a
52method parameter or return value, or a signal parameter value, must be of a
53type that is supported by the QML engine.
55By default, the engine supports a number of Qt C++ types and can automatically
56convert them as appropriately when used from QML. Additionally, C++ classes
57that are \l{Registering C++ types with the QML type system}{registered} with
58the QML type system can be used as data types, as can their enums if
59appropriately registered. See \l{qtqml-cppintegration-data.html}{Data Type
60Conversion Between QML and C++} for further information.
62Additionally, data ownership rules are taken into consideration when data is
63transferred from C++ to QML. See \l {Data Ownership} for more details.
66\section1 Exposing Properties
68A \e property can be specified for any QObject-derived class using the
69Q_PROPERTY() macro. A property is a class data member with an associated read
70function and optional write function.
72All properties of a QObject-derived or Q_GADGET class are accessible from QML.
74For example, below is a \c Message class with an \c author property. As
75specified by the Q_PROPERTY macro call, this property is readable through
76the \c author() method, and writable through the \c setAuthor() method:
78\note Do not use \e typedef or \e using for Q_PROPERTY types as these
79will confuse moc. This may make certain type comparisons fail.
84using FooEnum = Foo::Enum;
86class Bar : public QObject {
88 Q_PROPERTY(FooEnum enum READ enum WRITE setEnum NOTIFY enumChanged)
92Refer to the type directly:
95class Bar : public QObject {
97 Q_PROPERTY(Foo::Enum enum READ enum WRITE setEnum NOTIFY enumChanged)
102class Message : public QObject
105 Q_PROPERTY(QString author READ author WRITE setAuthor NOTIFY authorChanged)
107 void setAuthor(const QString &a) {
110 emit authorChanged();
113 QString author() const {
117 void authorChanged();
123If an instance of this class was \l{Embedding C++ Objects into QML with Context
124Properties}{set as a context property} when loading a file named \c MyItem.qml
128 int main(int argc, char *argv[]) {
129 QGuiApplication app(argc, argv);
133 view.engine()->rootContext()->setContextProperty("msg", &msg);
134 view.setSource(QUrl::fromLocalFile("MyItem.qml"));
141Then, the \c author property could be read from \c MyItem.qml:
148 width: 100; height: 100
149 text: msg.author // invokes Message::author() to get this value
151 Component.onCompleted: {
152 msg.author = "Jonah" // invokes Message::setAuthor()
157For maximum interoperability with QML, \b {any property that is writable should
158have an associated NOTIFY signal} that is emitted whenever the property value
159has changed. This allows the property to be used with \l{Property
160Binding}{property binding}, which is an essential feature of QML that enforces
161relationships between properties by automatically updating a property whenever
162any of its dependencies change in value.
164In the above example, the associated NOTIFY signal for the \c author property is
165\c authorChanged, as specified in the Q_PROPERTY() macro call. This means that
166whenever the signal is emitted — as it is when the author changes
167in Message::setAuthor() — this notifies the QML engine that any
168bindings involving the \c author property must be updated, and in turn, the
169engine will update the \c text property by calling \c Message::author() again.
171If the \c author property was writable but did not have an associated NOTIFY
172signal, the \c text value would be initialized with the initial value returned
173by \c Message::author() but would not be updated with any later changes to this
174property. In addition, any attempts to bind to the property from QML will
175produce a runtime warning from the engine.
177\note It is recommended that the NOTIFY signal be named \e <property>Changed
178where \c <property> is the name of the property. The associated property
179change signal handler generated by the QML engine will always take the form
180\c on<Property>Changed, regardless of the name of the related C++ signal, so
181it is recommended that the signal name follows this convention to avoid any
185\section3 Notes on Use of Notify Signals
187To prevent loops or excessive evaluation, developers should ensure that the
188property change signal is only emitted when the property value has actually
189changed. Also, if a property or group of properties is infrequently used, it
190is permitted to use the same NOTIFY signal for several properties. This should
191be done with care to ensure that performance doesn't suffer.
193The presence of a NOTIFY signal does incur a small overhead. There are cases
194where a property's value is set at object construction time, and does not
195subsequently change. The most common case of this is when a type uses \l
196{Grouped Properties}, and the grouped property object is allocated once, and
197only freed when the object is deleted. In these cases, the CONSTANT
198attribute may be added to the property declaration instead of a NOTIFY
201The CONSTANT attribute should only be used for properties whose value is set,
202and finalized, only in the class constructor. All other properties that want
203to be used in bindings should have a NOTIFY signal instead.
206\section2 Properties with Object Types
208Object-type properties are accessible from QML providing that the object type
209has been appropriately \l{Registering C++ types with the QML type
210system}{registered} with the QML type system.
212For example, the \c Message type might have a \c body property of type
216class Message : public QObject
219 Q_PROPERTY(MessageBody* body READ body WRITE setBody NOTIFY bodyChanged)
221 MessageBody* body() const;
222 void setBody(MessageBody* body);
225class MessageBody : public QObject
228 Q_PROPERTY(QString text READ text WRITE text NOTIFY textChanged)
233Suppose the \c Message type was \l{Registering C++ types with the QML type
234system}{registered} with the QML type system, allowing it to be used as an
235object type from QML code:
243If the \c MessageBody type was also registered with the type system, it would be
244possible to assign \c MessageBody to the \c body property of a \c Message, all
250 text: "Hello, world!"
256\section2 Properties with Object-List Types
258Properties containing lists of QObject-derived types can also be exposed to
259QML. For this purpose, however, one should use QQmlListProperty rather than
260QList<T> as the property type. This is because QList is not a QObject-derived
261type, and so cannot provide the necessary QML property characteristics
262through the Qt meta object system, such as signal notifications when a list
265For example, the \c MessageBoard class below has a \c messages property of
266type QQmlListProperty that stores a list of \c Message instances:
269class MessageBoard : public QObject
272 Q_PROPERTY(QQmlListProperty<Message> messages READ messages)
274 QQmlListProperty<Message> messages();
277 static void append_message(QQmlListProperty<Message> *list, Message *msg);
279 QList<Message *> m_messages;
283The MessageBoard::messages() function simply creates and returns a
284QQmlListProperty from its QList<T> \c m_messages member, passing the
285appropriate list modification functions as required by the QQmlListProperty
289QQmlListProperty<Message> MessageBoard::messages()
291 return QQmlListProperty<Message>(this, 0, &MessageBoard::append_message);
294void MessageBoard::append_message(QQmlListProperty<Message> *list, Message *msg)
296 MessageBoard *msgBoard = qobject_cast<MessageBoard *>(list->object);
298 msgBoard->m_messages.append(msg);
302Note that the template class type for the QQmlListProperty — in this case,
303\c Message — must be \l{Registering C++ types with the QML type system}
304{registered} with the QML type system.
307\section2 Grouped Properties
308\keyword Integrating QML and C++ - Grouped Properties
310Any read-only object-type property is accessible from QML code as a
311\e {grouped property}. This can be used to expose a group of related
312properties that describe a set of attributes for a type.
314For example, suppose the \c Message::author property was of type
315\c MessageAuthor rather than a simple string, with sub-properties
316of \c name and \c email:
319class MessageAuthor : public QObject
321 Q_PROPERTY(QString name READ name WRITE setName)
322 Q_PROPERTY(QString email READ email WRITE setEmail)
327class Message : public QObject
330 Q_PROPERTY(MessageAuthor* author READ author)
332 Message(QObject *parent)
333 : QObject(parent), m_author(new MessageAuthor(this))
336 MessageAuthor *author() const {
340 MessageAuthor *m_author;
344The \c author property could be written to using the
345\l{qtqml-syntax-objectattributes.html#grouped-properties}{grouped property
351 author.name: "Alexandra"
352 author.email: "alexandra@mail.com"
356A type that is exposed as a grouped property differs from an \l{Properties with
357Object Types}{object-type property} in that the grouped property is read-only,
358and is initialized to a valid value by the parent object at construction. The
359grouped property's sub-properties may be modified from QML but the grouped
360property object itself will never change, whereas an object-type property may be
361assigned a new object value from QML at any time. Thus, the lifetime of a
362grouped property object is controlled strictly by the C++ parent
363implementation, whereas an object-type property can be freely created and
364destroyed through QML code.
367\section1 Exposing Methods (Including Qt Slots)
369Any method of a QObject-derived type is accessible from QML code if it is:
372\li A public method flagged with the Q_INVOKABLE() macro
373\li A method that is a public Qt \l{Signals & Slots}{slot}
376For example, the \c MessageBoard class below has a \c postMessage() method that
377has been flagged with the Q_INVOKABLE macro, as well as a \c refresh() method
378that is a public slot:
381 class MessageBoard : public QObject
385 Q_INVOKABLE bool postMessage(const QString &msg) {
386 qDebug() << "Called the C++ method with" << msg;
392 qDebug() << "Called the C++ slot";
397If an instance of \c MessageBoard was set as the context data for a file \c
398MyItem.qml, then \c MyItem.qml could invoke the two methods as shown in the
406 int main(int argc, char *argv[]) {
407 QGuiApplication app(argc, argv);
409 MessageBoard msgBoard;
411 view.engine()->rootContext()->setContextProperty("msgBoard", &msgBoard);
412 view.setSource(QUrl::fromLocalFile("MyItem.qml"));
426 width: 100; height: 100
431 var result = msgBoard.postMessage("Hello from QML")
432 console.log("Result of postMessage():", result)
440If a C++ method has a parameter with a \c QObject* type, the parameter value
441can be passed from QML using an object \c id or a JavaScript \l var value
442that references the object.
444QML supports the calling of overloaded C++ functions. If there are multiple C++
445functions with the same name but different arguments, the correct function will
446be called according to the number and the types of arguments that are provided.
448Values returned from C++ methods are converted to JavaScript values when
449accessed from JavaScript expressions in QML.
451\section2 C++ methods and the 'this' object
453You may want to retrieve a C++ method from one object and call it on a different
454object. Consider the following example, within a QML module called \c{Example}:
461class Invokable : public QObject
466 Invokable(QObject *parent = nullptr) : QObject(parent) {}
468 Q_INVOKABLE void invoke() { qDebug() << "invoked on " << objectName(); }
480 property Invokable child: Invokable {}
481 Component.onCompleted: child.invoke.call(this)
486If you load the QML code from a suitable main.cpp, it should print
487"invoked on parent". However, due to a long standing bug, it doesn't.
488Historically, the 'this' object of C++-based methods is inseparably bound to
489the method. Changing this behavior for existing code would cause subtle errors
490since the 'this' object is implicit in many places. Since Qt 6.5 you can
491explicitly opt into the correct behavior and allow C++ methods to accept a
492'this' object. To do so, add the following pragma to your QML documents:
495pragma NativeMethodBehavior: AcceptThisObject
498With this line added, the example above will work as expected.
500\section1 Exposing Signals
502Any public \l{Signals & Slots}{signal} of a QObject-derived type is accessible
505The QML engine automatically creates a \l{Signal and Handler Event
506System}{signal handler} for any signal of a QObject-derived type that is used
507from QML. Signal handlers are always named \e on<Signal> where \c <Signal> is
508the name of the signal, with the first letter capitalized. All parameters passed
509by the signal are available in the signal handler through the parameter names.
511For example, suppose the \c MessageBoard class has a \c newMessagePosted()
512signal with a single parameter, \c subject:
515 class MessageBoard : public QObject
521 void newMessagePosted(const QString &subject);
525If the \c MessageBoard type was \l{Registering C++ types with the QML type
526system}{registered} with the QML type system, then a \c MessageBoard object
527declared in QML could receive the \c newMessagePosted() signal using a signal
528handler named \c onNewMessagePosted, and examine the \c subject parameter
533 onNewMessagePosted: (subject)=> console.log("New message received:", subject)
537As with property values and method parameters, a signal parameter must have a
538type that is supported by the QML engine; see
539\l {Data Type Conversion Between QML and C++}. (Using an
540unregistered type will not generate an error, but the parameter value will
541not be accessible from the handler.)
543Classes may have multiple signals with the same name, but only the final
544signal is accessible as a QML signal. Note that signals with the same name
545but different parameters cannot be distinguished from one another.