Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
src_qml_qqmlengine.cpp
Go to the documentation of this file.
1// Copyright (C) 2020 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
3
4//! [0]
5class MySingleton : public QObject {
6 Q_OBJECT
7
8 // Register as default constructed singleton.
9 QML_ELEMENT
11
12 static int typeId;
13 // ...
14};
15//! [0]
16
17/*
18//! [1]
19 MySingleton::typeId = qmlTypeId(...);
20//! [1]
21*/
22
23void wrapper2() {
24//! [2]
25 // Retrieve as QObject*
26 QQmlEngine engine;
27 MySingleton* instance = engine.singletonInstance<MySingleton*>(MySingleton::typeId);
28//! [2]
29}
30
31/*
32//! [3]
33 // Register with QJSValue callback
34 int typeId = qmlRegisterSingletonType(...);
35//! [3]
36*/
37
38void wrapper4(int typeId) {
39//! [4]
40 // Retrieve as QJSValue
41 QQmlEngine engine;
42 QJSValue instance = engine.singletonInstance<QJSValue>(typeId);
43//! [4]
44}
45
46void wrapper5() {
47//! [5]
48 QQmlEngine engine;
49 MySingleton *singleton = engine.singletonInstance<MySingleton *>("mymodule", "MySingleton");
50//! [5]
51}
52
54
55//! [6]
56class CppSingleton: public QObject {
57 Q_OBJECT
58 QML_ELEMENT
60 QML_UNCREATABLE("Provided via QQmlEngine::setExternalSingletonInstance")
61 // Q_PROPERTY(...)
62public:
63 explicit CppSingleton(BackendService *service); // constructor taking a reference to something MySingleton needs
64 // members, Q_INVOKABLE functions, etc.
65};
66//! [6]
67
68void wrapper6() {
69//! [7]
70 // create and setup the backend service
71 BackendService service;
72
73 // create your singleton instance
74 CppSingleton singleton(&service);
75 QQmlApplicationEngine engine;
76 engine.setExternalSingletonInstance("com.company.myApp", "MySingleton", &singleton);
77 engine.loadFromModule("com.company.myApp", "Main");
78//! [7]
79}
void wrapper2()
[0]
void wrapper6()
[6]
void wrapper5()
void wrapper4(int typeId)