QQmlEngine 类

The QQmlEngine class provides an environment for instantiating QML components. 更多...

头: #include <QQmlEngine>
qmake: QT += qml
Since: Qt 5.0
继承: QJSEngine
继承者: QQmlApplicationEngine

公共类型

enum ObjectOwnership { CppOwnership, JavaScriptOwnership }

特性

公共函数

QQmlEngine (QObject * parent = Q_NULLPTR)
virtual ~QQmlEngine ()
void addImageProvider (const QString & providerId , QQmlImageProviderBase * provider )
void addImportPath (const QString & path )
void addPluginPath (const QString & path )
QUrl baseUrl () const
void clearComponentCache ()
QQmlImageProviderBase * imageProvider (const QString & providerId ) const
QStringList importPathList () const
bool importPlugin (const QString & filePath , const QString & uri , QList<QQmlError> * errors )
QQmlIncubationController * incubationController () const
QNetworkAccessManager * networkAccessManager () const
QQmlNetworkAccessManagerFactory * networkAccessManagerFactory () const
QString offlineStorageDatabaseFilePath (const QString & databaseName ) const
QString offlineStoragePath () const
bool outputWarningsToStandardError () const
QStringList pluginPathList () const
void removeImageProvider (const QString & providerId )
QQmlContext * rootContext () const
void setBaseUrl (const QUrl & url )
void setImportPathList (const QStringList & paths )
void setIncubationController (QQmlIncubationController * controller )
void setNetworkAccessManagerFactory (QQmlNetworkAccessManagerFactory * factory )
void setOfflineStoragePath (const QString & dir )
void setOutputWarningsToStandardError (bool enabled )
void setPluginPathList (const QStringList & paths )
void trimComponentCache ()

信号

void exit (int retCode )
void quit ()
void warnings (const QList<QQmlError> & warnings )

静态公共成员

QQmlContext * contextForObject (const QObject * object )
ObjectOwnership objectOwnership (QObject * object )
void setContextForObject (QObject * object , QQmlContext * context )
void setObjectOwnership (QObject * object , ObjectOwnership ownership )

重实现保护函数

virtual bool event (QEvent * e ) override
QObject * qmlAttachedPropertiesObject (const QObject * attachee , bool create = true)
void qmlClearTypeRegistrations ()
QQmlContext * qmlContext (const QObject * object )
QQmlInfo qmlDebug (const QObject * object )
QQmlEngine * qmlEngine (const QObject * object )
QQmlInfo qmlInfo (const QObject * object )
bool qmlProtectModule (const char * uri , int majVersion )
int qmlRegisterExtendedType (const char * uri , int versionMajor , int versionMinor , const char * qmlName )
int qmlRegisterExtendedUncreatableType (const char * uri , int versionMajor , int versionMinor , const char * qmlName , const QString & reason )
int qmlRegisterInterface (const char * typeName )
void qmlRegisterModule (const char * uri , int versionMajor , int versionMinor )
int qmlRegisterRevision (const char * uri , int versionMajor , int versionMinor )
int qmlRegisterSingletonType (const char * uri , int versionMajor , int versionMinor , const char * typeName , QJSValue(* ) ( QQmlEngine *, QJSEngine * ) callback )
int qmlRegisterSingletonType (const char * uri , int versionMajor , int versionMinor , const char * typeName , QObject *(* ) ( QQmlEngine *, QJSEngine * ) callback )
int qmlRegisterSingletonType (const QUrl & url , const char * uri , int versionMajor , int versionMinor , const char * qmlName )
int qmlRegisterType ()
int qmlRegisterType (const char * uri , int versionMajor , int versionMinor , const char * qmlName )
int qmlRegisterType (const QUrl & url , const char * uri , int versionMajor , int versionMinor , const char * qmlName )
int qmlRegisterTypeNotAvailable (const char * uri , int versionMajor , int versionMinor , const char * qmlName , const QString & message )
int qmlRegisterUncreatableMetaObject (const QMetaObject & staticMetaObject , const char * uri , int versionMajor , int versionMinor , const char * qmlName , const QString & reason )
int qmlRegisterUncreatableType (const char * uri , int versionMajor , int versionMinor , const char * qmlName , const QString & message )
QQmlInfo qmlWarning (const QObject * object )

QML_DECLARE_TYPE ()
QML_DECLARE_TYPEINFO ( Type , Flags )

额外继承成员

详细描述

The QQmlEngine class provides an environment for instantiating QML components.

每个 QML 组件被实例化在 QQmlContext . QQmlContext 's are essential for passing data to QML components. In QML, contexts are arranged hierarchically and this hierarchy is managed by the QQmlEngine .

Prior to creating any QML components, an application must have created a QQmlEngine to gain access to a QML context. The following example shows how to create a simple Text item.

QQmlEngine engine;
QQmlComponent component(&engine);
component.setData("import QtQuick 2.0\nText { text: \"Hello world!\" }", QUrl());
QQuickItem *item = qobject_cast<QQuickItem *>(component.create());
//add item to view, etc
...
					

In this case, the Text item will be created in the engine's 根上下文 .

注意, Qt Quick 1 version is called QDeclarativeEngine.

另请参阅 QQmlComponent , QQmlContext ,和 QML 全局对象 .

成员类型文档编制

enum QQmlEngine:: ObjectOwnership

ObjectOwnership controls whether or not QML automatically destroys the QObject when the corresponding JavaScript object is garbage collected by the engine. The two ownership options are:

常量 描述
QQmlEngine::CppOwnership 0 The object is owned by C++ code and QML will never delete it. The JavaScript destroy() method cannot be used on these objects. This option is similar to QScriptEngine::QtOwnership .
QQmlEngine::JavaScriptOwnership 1 The object is owned by JavaScript. When the object is returned to QML as the return value of a method call, QML will track it and delete it if there are no remaining JavaScript references to it and it has no QObject::parent (). An object tracked by one QQmlEngine will be deleted during that QQmlEngine 's destructor. Thus, JavaScript references between objects with JavaScriptOwnership from two different engines will not be valid if one of these engines is deleted. This option is similar to QScriptEngine::ScriptOwnership .

Generally an application doesn't need to set an object's ownership explicitly. QML uses a heuristic to set the default ownership. By default, an object that is created by QML has JavaScriptOwnership. The exception to this are the root objects created by calling QQmlComponent::create () 或 QQmlComponent::beginCreate (), which have CppOwnership by default. The ownership of these root-level objects is considered to have been transferred to the C++ caller.

Objects not-created by QML have CppOwnership by default. The exception to this are objects returned from C++ method calls; their ownership will be set to JavaScriptOwnership. This applies only to explicit invocations of Q_INVOKABLE methods or slots, but not to property getter invocations.

调用 setObjectOwnership () overrides the default ownership heuristic used by QML.

特性文档编制

offlineStoragePath : QString

This property holds the directory for storing offline user data

Returns the directory where SQL and other offline storage is placed.

The SQL databases created with openDatabase() are stored here.

The default is QML/OfflineStorage in the platform-standard user application data directory.

Note that the path may not currently exist on the filesystem, so callers wanting to create new files at this location should create it first - see QDir::mkpath ().

访问函数:

QString offlineStoragePath () const
void setOfflineStoragePath (const QString & dir )

成员函数文档编制

QQmlEngine:: QQmlEngine ( QObject * parent = Q_NULLPTR)

创建新的 QQmlEngine 采用给定 parent .

[虚拟] QQmlEngine:: ~QQmlEngine ()

销毁 QQmlEngine .

任何 QQmlContext 's created on this engine will be invalidated, but not destroyed (unless they are parented to the QQmlEngine 对象)。

QJSEngine docs for details on cleaning up the JS engine.

void QQmlEngine:: addImageProvider (const QString & providerId , QQmlImageProviderBase * provider )

设置 provider to use for images requested via the image : url scheme, with host providerId QQmlEngine 拥有所有权对于 provider .

Image providers enable support for pixmap and threaded image requests. See the QQuickImageProvider documentation for details on implementing and using image providers.

All required image providers should be added to the engine before any QML sources files are loaded.

另请参阅 removeImageProvider (), QQuickImageProvider ,和 QQmlImageProviderBase .

void QQmlEngine:: addImportPath (const QString & path )

添加 path as a directory where the engine searches for installed modules in a URL-based directory structure.

The path may be a local filesystem directory, a Qt Resource path ( :/imports ), Qt Resource url ( qrc:/imports ) 或 URL。

The path will be converted into canonical form before it is added to the import path list.

The newly added path will be first in the importPathList ().

另请参阅 setImportPathList () 和 QML 模块 .

void QQmlEngine:: addPluginPath (const QString & path )

添加 path as a directory where the engine searches for native plugins for imported modules (referenced in the qmldir file).

By default, the list contains only . , i.e. the engine searches in the directory of the qmldir file itself.

The newly added path will be first in the pluginPathList ().

另请参阅 setPluginPathList ().

QUrl QQmlEngine:: baseUrl () const

Return the base URL for this engine. The base URL is only used to resolve components when a relative URL is passed to the QQmlComponent 构造函数。

If a base URL has not been explicitly set, this method returns the application's current working directory.

另请参阅 setBaseUrl ().

void QQmlEngine:: clearComponentCache ()

Clears the engine's internal component cache.

This function causes the property metadata of all components previously loaded by the engine to be destroyed. All previously loaded components and the property bindings for all extant objects created from those components will cease to function.

This function returns the engine to a state where it does not contain any loaded component data. This may be useful in order to reload a smaller subset of the previous component set, or to load a new version of a previously loaded component.

Once the component cache has been cleared, components must be loaded before any new objects can be created.

另请参阅 trimComponentCache ().

[static] QQmlContext *QQmlEngine:: contextForObject (const QObject * object )

返回 QQmlContext object , or 0 if no context has been set.

QQmlEngine instantiates a QObject , the context is set automatically.

另请参阅 setContextForObject (), qmlContext (),和 qmlEngine ().

[override virtual protected] bool QQmlEngine:: event ( QEvent * e )

重实现自 QObject::event ().

[signal] void QQmlEngine:: exit ( int retCode )

This signal is emitted when the QML loaded by the engine would like to exit from the event loop with the specified return code retCode .

该函数在 Qt 5.8 引入。

另请参阅 quit ().

QQmlImageProviderBase *QQmlEngine:: imageProvider (const QString & providerId ) const

Returns the image provider set for providerId .

Returns the provider if it was found; otherwise returns 0.

另请参阅 QQuickImageProvider .

QStringList QQmlEngine:: importPathList () const

Returns the list of directories where the engine searches for installed modules in a URL-based directory structure.

例如,若 /opt/MyApp/lib/imports is in the path, then QML that imports com.mycompany.Feature will cause the QQmlEngine to look in /opt/MyApp/lib/imports/com/mycompany/Feature/ for the components provided by that module. A qmldir file is required for defining the type version mapping and possibly QML extensions plugins.

By default, the list contains the directory of the application executable, paths specified in the QML2_IMPORT_PATH environment variable, and the builtin Qml2ImportsPath from QLibraryInfo .

另请参阅 addImportPath () 和 setImportPathList ().

bool QQmlEngine:: importPlugin (const QString & filePath , const QString & uri , QList < QQmlError > * errors )

Imports the plugin named filePath 采用 uri provided. Returns true if the plugin was successfully imported; otherwise returns false.

On failure and if non-null, the errors list will have any errors which occurred prepended to it.

The plugin has to be a Qt plugin which implements the QQmlExtensionPlugin 接口。

QQmlIncubationController *QQmlEngine:: incubationController () const

Returns the currently set incubation controller, or 0 if no controller has been set.

另请参阅 setIncubationController ().

QNetworkAccessManager *QQmlEngine:: networkAccessManager () const

Returns a common QNetworkAccessManager which can be used by any QML type instantiated by this engine.

QQmlNetworkAccessManagerFactory has been set and a QNetworkAccessManager has not yet been created, the QQmlNetworkAccessManagerFactory will be used to create the QNetworkAccessManager ; otherwise the returned QNetworkAccessManager will have no proxy or cache set.

另请参阅 setNetworkAccessManagerFactory ().

QQmlNetworkAccessManagerFactory *QQmlEngine:: networkAccessManagerFactory () const

返回当前 QQmlNetworkAccessManagerFactory .

另请参阅 setNetworkAccessManagerFactory ().

[static] ObjectOwnership QQmlEngine:: objectOwnership ( QObject * object )

Returns the ownership of object .

另请参阅 setObjectOwnership ().

QString QQmlEngine:: offlineStorageDatabaseFilePath (const QString & databaseName ) const

Returns the file path where a 本地存储 database with the identifier databaseName is (or would be) located.

该函数在 Qt 5.9 引入。

另请参阅 LocalStorage.openDatabaseSync ().

bool QQmlEngine:: outputWarningsToStandardError () const

Returns true if warning messages will be output to stderr in addition to being emitted by the warnings () 信号,否则 false。

默认值为 true。

另请参阅 setOutputWarningsToStandardError ().

QStringList QQmlEngine:: pluginPathList () const

Returns the list of directories where the engine searches for native plugins for imported modules (referenced in the qmldir file).

By default, the list contains only . , i.e. the engine searches in the directory of the qmldir file itself.

另请参阅 addPluginPath () 和 setPluginPathList ().

[signal] void QQmlEngine:: quit ()

This signal is emitted when the QML loaded by the engine would like to quit.

另请参阅 exit ().

void QQmlEngine:: removeImageProvider (const QString & providerId )

Removes the image provider for providerId .

另请参阅 addImageProvider () 和 QQuickImageProvider .

QQmlContext *QQmlEngine:: rootContext () const

返回引擎的根上下文。

The root context is automatically created by the QQmlEngine . Data that should be available to all QML component instances instantiated by the engine should be put in the root context.

Additional data that should only be available to a subset of component instances should be added to sub-contexts parented to the root context.

void QQmlEngine:: setBaseUrl (const QUrl & url )

Set the base URL for this engine to url .

另请参阅 baseUrl ().

[static] void QQmlEngine:: setContextForObject ( QObject * object , QQmlContext * context )

设置 QQmlContext object to context 。若 object already has a context, a warning is output, but the context is not changed.

QQmlEngine instantiates a QObject , the context is set automatically.

另请参阅 contextForObject ().

void QQmlEngine:: setImportPathList (const QStringList & paths )

paths as the list of directories where the engine searches for installed modules in a URL-based directory structure.

By default, the list contains the directory of the application executable, paths specified in the QML2_IMPORT_PATH environment variable, and the builtin Qml2ImportsPath from QLibraryInfo .

另请参阅 importPathList () 和 addImportPath ().

void QQmlEngine:: setIncubationController ( QQmlIncubationController * controller )

Sets the engine's incubation controller . The engine can only have one active controller and it does not take ownership of it.

另请参阅 incubationController ().

void QQmlEngine:: setNetworkAccessManagerFactory ( QQmlNetworkAccessManagerFactory * factory )

设置 factory to use for creating QNetworkAccessManager (s).

QNetworkAccessManager is used for all network access by QML. By implementing a factory it is possible to create custom QNetworkAccessManager with specialized caching, proxy and cookie support.

The factory must be set before executing the engine.

另请参阅 networkAccessManagerFactory ().

[static] void QQmlEngine:: setObjectOwnership ( QObject * object , ObjectOwnership ownership )

设置 ownership of object .

另请参阅 objectOwnership ().

void QQmlEngine:: setOutputWarningsToStandardError ( bool enabled )

Set whether warning messages will be output to stderr to enabled .

enabled is true, any warning messages generated by QML will be output to stderr and emitted by the warnings () signal. If enabled is false, only the warnings () signal will be emitted. This allows applications to handle warning output themselves.

默认值为 true。

另请参阅 outputWarningsToStandardError ().

void QQmlEngine:: setPluginPathList (const QStringList & paths )

Sets the list of directories where the engine searches for native plugins for imported modules (referenced in the qmldir file) to paths .

By default, the list contains only . , i.e. the engine searches in the directory of the qmldir file itself.

另请参阅 pluginPathList () 和 addPluginPath ().

void QQmlEngine:: trimComponentCache ()

Trims the engine's internal component cache.

This function causes the property metadata of any loaded components which are not currently in use to be destroyed.

A component is considered to be in use if there are any extant instances of the component itself, any instances of other components that use the component, or any objects instantiated by any of those components.

另请参阅 clearComponentCache ().

[signal] void QQmlEngine:: warnings (const QList < QQmlError > & warnings )

此信号被发射当 warnings messages are generated by QML.

相关非成员

QObject * qmlAttachedPropertiesObject (const QObject * attachee , bool create = true)

The form of this template function is:

template<typename T> QObject *qmlAttachedPropertiesObject(const QObject *attachee, bool create = true)
					

This returns the attached object instance that has been attached to the specified attachee by the attaching type T .

create is true and type T is a valid attaching type, this creates and returns a new attached object instance.

Returns 0 if type T is not a valid attaching type, or if create is false and no attachment object instance has previously been created for attachee .

另请参阅 Providing Attached Properties .

void qmlClearTypeRegistrations ()

Clears all stored type registrations, such as those produced with qmlRegisterType ().

Do not call this function while a QQmlEngine exists or behavior will be undefined. Any existing QQmlEngines must be deleted before calling this function. This function only affects the application global cache. Delete the QQmlEngine to clear all cached data relating to that engine.

QQmlContext * qmlContext (const QObject * object )

返回 QQmlContext associated with object , if any. This is equivalent to QQmlEngine::contextForObject (object).

注意: 添加 #include <QtQml> to use this function.

另请参阅 contextForObject () 和 qmlEngine ().

QQmlInfo QtQml:: qmlDebug (const QObject * object )

Prints debug messages that include the file and line number for the specified QML object .

When QML types produce logging messages, it improves traceability if they include the QML file and line number on which the particular instance was instantiated.

To include the file and line number, an object must be passed. If the file and line number is not available for that instance (either it was not instantiated by the QML engine or location information is disabled), "unknown location" will be used instead.

例如,

qmlDebug(object) << "Internal state: 42";
					

prints

QML MyCustomType (unknown location): Internal state: 42
					

该函数在 Qt 5.9 引入。

另请参阅 QtQml::qmlInfo and QtQml::qmlWarning .

QQmlEngine * qmlEngine (const QObject * object )

返回 QQmlEngine associated with object , if any. This is equivalent to QQmlEngine::contextForObject (object)->engine(), but more efficient.

注意: 添加 #include <QtQml> to use this function.

另请参阅 contextForObject () 和 qmlContext ().

QQmlInfo QtQml:: qmlInfo (const QObject * object )

Prints informational messages that include the file and line number for the specified QML object .

When QML types produce logging messages, it improves traceability if they include the QML file and line number on which the particular instance was instantiated.

To include the file and line number, an object must be passed. If the file and line number is not available for that instance (either it was not instantiated by the QML engine or location information is disabled), "unknown location" will be used instead.

例如,

qmlInfo(object) << tr("component property is a write-once property");
					

prints

QML MyCustomType (unknown location): component property is a write-once property
					

注意: In versions prior to Qt 5.9, qmlInfo reported messages using a warning QtMsgType . For Qt 5.9 and above, qmlInfo uses an info QtMsgType . To send warnings, use qmlWarning .

另请参阅 QtQml::qmlDebug and QtQml::qmlWarning .

bool qmlProtectModule (const char * uri , int majVersion )

This function protects a module from having types registered into it. This can be used to prevent other plugins from injecting types into your module. It can also be a performance improvement, as it allows the engine to skip checking for the possibility of new types or plugins when this import is reached.

The performance benefit is primarily seen when registering application specific types from within the application instead of through a plugin. Using qmlProtectModule allows the engine to skip checking for a plugin when that uri is imported, which can be noticeable with slow file systems.

After this function is called, any attempt to register C++ types into this uri, major version combination will lead to a runtime error. Call this after you have registered all of your types with the engine.

Returns true if the module with uri 作为 模块标识符 and majVersion as a major version number was found and locked, otherwise returns false. The module must contain exported types in order to be found.

int qmlRegisterExtendedType (const char * uri , int versionMajor , int versionMinor , const char * qmlName )

This template function registers the C++ type and its extension object in the QML system with the name qmlName in the library imported from uri having version number composed from versionMajor and versionMinor . Properties not available in the main type will be searched for in the extension object.

返回 QML 类型 ID。

另请参阅 qmlRegisterType () 和 Registering Extension Objects .

int qmlRegisterExtendedUncreatableType (const char * uri , int versionMajor , int versionMinor , const char * qmlName , const QString & reason )

This template function registers the C++ type and its extension in the QML system with the name qmlName in the library imported from uri having version number composed from versionMajor and versionMinor .

While the type has a name and a type, it cannot be created. An error message with the given reason is printed if the user attempts to create an instance of this type.

This is useful where the type is only intended for providing attached properties, enum values or an abstract base class with its extension.

返回 QML 类型 ID。

另请参阅 qmlRegisterUncreatableType ().

int qmlRegisterInterface (const char * typeName )

This template function registers the C++ type in the QML system under the name typeName .

返回 QML 类型 ID。

void qmlRegisterModule (const char * uri , int versionMajor , int versionMinor )

This function registers a module in a particular uri with a version specified in versionMajor and versionMinor .

This can be used to make a certain module version available, even if no types are registered for that version. This is particularly useful for keeping the versions of related modules in sync.

该函数在 Qt 5.9 引入。

int qmlRegisterRevision (const char * uri , int versionMajor , int versionMinor )

This template function registers the specified revision of a C++ type in the QML system with the library imported from uri having the version number composed from versionMajor and versionMinor .

返回 QML 类型 ID。

template<typename T, int metaObjectRevision>
int qmlRegisterRevision(const char *uri, int versionMajor, int versionMinor);
					

This function is typically used to register the revision of a base class to use for the specified version of the type (see Type Revisions and Versions ).

int qmlRegisterSingletonType (const char * uri , int versionMajor , int versionMinor , const char * typeName , QJSValue (* ) ( QQmlEngine *, QJSEngine * ) callback )

This function may be used to register a singleton type provider callback in a particular uri and typeName with a version specified in versionMajor and versionMinor .

Installing a singleton type allows developers to provide arbitrary functionality (methods and properties) to a client without requiring individual instances of the type to be instantiated by the client.

A singleton type may be either a QObject QJSValue . This function should be used to register a singleton type provider function which returns a QJSValue as a singleton type.

NOTE: QJSValue singleton type properties will not trigger binding re-evaluation if changed.

用法:

// First, define the singleton type provider function (callback).
static QJSValue example_qjsvalue_singletontype_provider(QQmlEngine *engine, QJSEngine *scriptEngine)
{
    Q_UNUSED(engine)
    static int seedValue = 5;
    QJSValue example = scriptEngine->newObject();
    example.setProperty("someProperty", seedValue++);
    return example;
}
// Second, register the singleton type provider with QML by calling this function in an initialization function.
qmlRegisterSingletonType("Qt.example.qjsvalueApi", 1, 0, "MyApi", example_qjsvalue_singletontype_provider);
					

Alternatively, you can use a C++11 lambda:

qmlRegisterSingletonType("Qt.example.qjsvalueApi", 1, 0, "MyApi", [](QQmlEngine *engine, QJSEngine *scriptEngine) -> QJSValue {
    Q_UNUSED(engine)
    static int seedValue = 5;
    QJSValue example = scriptEngine->newObject();
    example.setProperty("someProperty", seedValue++);
    return example;
});
					

In order to use the registered singleton type in QML, you must import the singleton type.

import QtQuick 2.0
import Qt.example.qjsvalueApi 1.0 as ExampleApi
Item {
    id: root
    property int someValue: ExampleApi.MyApi.someProperty
}
					

int qmlRegisterSingletonType (const char * uri , int versionMajor , int versionMinor , const char * typeName , QObject *(* ) ( QQmlEngine *, QJSEngine * ) callback )

This function may be used to register a singleton type provider callback in a particular uri and typeName with a version specified in versionMajor and versionMinor .

Installing a singleton type into a uri allows developers to provide arbitrary functionality (methods and properties) to clients without requiring individual instances ot the type to be instantiated by the client.

A singleton type may be either a QObject QJSValue . This function should be used to register a singleton type provider function which returns a QObject of the given type T as a singleton type.

A QObject singleton type may be referenced via the type name with which it was registered, and this typename may be used as the target in a Connections type or otherwise used as any other type id would. One exception to this is that a QObject singleton type property may not be aliased (because the singleton type name does not identify an object within the same component as any other item).

NOTE: A QObject singleton type instance returned from a singleton type provider is owned by the QML engine unless the object has explicit QQmlEngine::CppOwnership 设置标志。

用法:

// First, define your QObject which provides the functionality.
class SingletonTypeExample : public QObject
{
    Q_OBJECT
    Q_PROPERTY (int someProperty READ someProperty WRITE setSomeProperty NOTIFY somePropertyChanged)
public:
    SingletonTypeExample(QObject* parent = 0)
        : QObject(parent), m_someProperty(0)
    {
    }
    ~SingletonTypeExample() {}
    Q_INVOKABLE int doSomething() { setSomeProperty(5); return m_someProperty; }
    int someProperty() const { return m_someProperty; }
    void setSomeProperty(int val) { m_someProperty = val; emit somePropertyChanged(val); }
signals:
    void somePropertyChanged(int newValue);
private:
    int m_someProperty;
};
// Second, define the singleton type provider function (callback).
static QObject *example_qobject_singletontype_provider(QQmlEngine *engine, QJSEngine *scriptEngine)
{
    Q_UNUSED(engine)
    Q_UNUSED(scriptEngine)
    SingletonTypeExample *example = new SingletonTypeExample();
    return example;
}
// Third, register the singleton type provider with QML by calling this function in an initialization function.
qmlRegisterSingletonType<SingletonTypeExample>("Qt.example.qobjectSingleton", 1, 0, "MyApi", example_qobject_singletontype_provider);
					

Alternatively, you can use a C++11 lambda:

qmlRegisterSingletonType<SingletonTypeExample>("Qt.example.qjsvalueApi", 1, 0, "MyApi", [](QQmlEngine *engine, QJSEngine *scriptEngine) -> QObject * {
    Q_UNUSED(engine)
    Q_UNUSED(scriptEngine)
    SingletonTypeExample *example = new SingletonTypeExample();
    return example;
});
					

In order to use the registered singleton type in QML, you must import the singleton type.

import QtQuick 2.0
import Qt.example.qobjectSingleton 1.0
Item {
    id: root
    property int someValue: MyApi.someProperty
    Component.onCompleted: {
        someValue = MyApi.doSomething()
    }
}
					

Since singleton types do not have an associated QQmlContext object, then within the functions of a QObject -derived type that is registered as a singleton type implementation the QML context and engine information is not available. The QQmlEngine::contextForObject () function returns NULL when supplied with a pointer to an QObject that implements a singleton type.

Extending the above example:

class SingletonTypeExample : public QObject
{
    ...
    Q_INVOKABLE void doSomethingElse()
    {
        // QML Engine/Context information is not accessible here:
        Q_ASSERT(QQmlEngine::contextForObject(this) == 0);
        Q_ASSERT(qmlContext(this) == 0);
        Q_ASSERT(qmlEngine(this) == 0);
    }
    ...
}
					

int qmlRegisterSingletonType (const QUrl & url , const char * uri , int versionMajor , int versionMinor , const char * qmlName )

This function may be used to register a singleton type with the name qmlName , in the library imported from uri having the version number composed from versionMajor and versionMinor . The type is defined by the QML file located at url . The url must be an absolute URL, i.e. url.isRelative() == false.

In addition the type's QML file must have pragma Singleton statement among its import statements.

A singleton type may be referenced via the type name with which it was registered, and this typename may be used as the target in a Connections type or otherwise used as any other type id would. One exception to this is that a singleton type property may not be aliased (because the singleton type name does not identify an object within the same component as any other item).

用法:

// First, define your QML singleton type which provides the functionality.
pragma Singleton
import QtQuick 2.0
Item {
    property int testProp1: 125
}
					
// Second, register the QML singleton type by calling this function in an initialization function.
qmlRegisterSingletonType(QUrl("file:///absolute/path/SingletonType.qml"), "Qt.example.qobjectSingleton", 1, 0, "RegisteredSingleton");
					

In order to use the registered singleton type in QML, you must import the singleton type.

import QtQuick 2.0
import Qt.example.qobjectSingleton 1.0
Item {
    id: root
    property int someValue: RegisteredSingleton.testProp1
}
					

It is also possible to have QML singleton types registered without using the qmlRegisterSingletonType function. That can be done by adding a pragma Singleton statement among the imports of the type's QML file. In addition the type must be defined in a qmldir file with a singleton keyword and the qmldir must be imported by the QML files using the singleton.

int qmlRegisterType ()

这是重载函数。

This template function registers the C++ type in the QML system. Instances of this type cannot be created from the QML system.

返回 QML 类型 ID。

int qmlRegisterType (const char * uri , int versionMajor , int versionMinor , const char * qmlName )

This template function registers the C++ type in the QML system with the name qmlName , in the library imported from uri having the version number composed from versionMajor and versionMinor .

返回 QML 类型 ID。

There are two forms of this template function:

template<typename T>
int qmlRegisterType(const char *uri, int versionMajor, int versionMinor, const char *qmlName);
template<typename T, int metaObjectRevision>
int qmlRegisterType(const char *uri, int versionMajor, int versionMinor, const char *qmlName);
					

The former is the standard form which registers the type T as a new type. The latter allows a particular revision of a class to be registered in a specified version (see Type Revisions and Versions ).

For example, this registers a C++ class MySliderItem as a QML type named Slider for version 1.0 of a type namespace called "com.mycompany.qmlcomponents":

qmlRegisterType<MySliderItem>("com.mycompany.qmlcomponents", 1, 0, "Slider");
					

Once this is registered, the type can be used in QML by importing the specified type namespace and version number:

import com.mycompany.qmlcomponents 1.0
Slider {
    // ...
}
					

Note that it's perfectly reasonable for a library to register types to older versions than the actual version of the library. Indeed, it is normal for the new library to allow QML written to previous versions to continue to work, even if more advanced versions of some of its types are available.

int qmlRegisterType (const QUrl & url , const char * uri , int versionMajor , int versionMinor , const char * qmlName )

This function registers a type in the QML system with the name qmlName , in the library imported from uri having the version number composed from versionMajor and versionMinor . The type is defined by the QML file located at url . The url must be an absolute URL, i.e. url.isRelative() == false.

Normally QML files can be loaded as types directly from other QML files, or using a qmldir file. This function allows registration of files to types from C++ code, such as when the type mapping needs to be procedurally determined at startup.

Returns -1 if the registration was not successful.

int qmlRegisterTypeNotAvailable (const char * uri , int versionMajor , int versionMinor , const char * qmlName , const QString & message )

This function registers a type in the QML system with the name qmlName , in the type namespace imported from uri having the version number composed from versionMajor and versionMinor , but any attempt to instantiate the type will produce the given error message .

Normally, the types exported by a plugin should be fixed. However, if a C++ type is not available, you should at least "reserve" the QML type name, and give the user of the unavailable type a meaningful error message.

返回 QML 类型 ID。

范例:

#ifdef NO_GAMES_ALLOWED
qmlRegisterTypeNotAvailable("MinehuntCore", 0, 1, "Game", "Get back to work, slacker!");
#else
qmlRegisterType<MinehuntGame>("MinehuntCore", 0, 1, "Game");
#endif
					

This will cause any QML which imports the "MinehuntCore" type namespace and attempts to use the type to produce an error message:

fun.qml: Get back to work, slacker!
   Game {
   ^
					

Without this, a generic "Game is not a type" message would be given.

另请参阅 qmlRegisterUncreatableType ().

int qmlRegisterUncreatableMetaObject (const QMetaObject & staticMetaObject , const char * uri , int versionMajor , int versionMinor , const char * qmlName , const QString & reason )

This function registers the staticMetaObject and its extension in the QML system with the name qmlName in the library imported from uri having version number composed from versionMajor and versionMinor .

An instance of the meta object cannot be created. An error message with the given reason is printed if the user attempts to create it.

This function is useful for registering Q_NAMESPACE namespaces.

返回 QML 类型 ID。

例如:

namespace MyNamespace {
  Q_NAMESPACE
  enum MyEnum {
      Key1,
      Key2,
  };
  Q_ENUMS(MyEnum)
}
//...
qmlRegisterUncreatableMetaObject(MyNamespace::staticMetaObject, "io.qt", 1, 0, "MyNamespace", "Access to enums & flags only");
					

On the QML side, you can now use the registered enums:

Component.onCompleted: console.log(MyNamespace.Key2)
					

该函数在 Qt 5.8 引入。

int qmlRegisterUncreatableType (const char * uri , int versionMajor , int versionMinor , const char * qmlName , const QString & message )

This template function registers the C++ type in the QML system with the name qmlName , in the library imported from uri having the version number composed from versionMajor and versionMinor .

While the type has a name and a type, it cannot be created, and the given error message will result if creation is attempted.

This is useful where the type is only intended for providing attached properties or enum values.

返回 QML 类型 ID。

另请参阅 qmlRegisterTypeNotAvailable ().

QQmlInfo QtQml:: qmlWarning (const QObject * object )

Prints warning messages that include the file and line number for the specified QML object .

When QML types produce logging messages, it improves traceability if they include the QML file and line number on which the particular instance was instantiated.

To include the file and line number, an object must be passed. If the file and line number is not available for that instance (either it was not instantiated by the QML engine or location information is disabled), "unknown location" will be used instead.

例如,

qmlInfo(object) << tr("property cannot be set to 0");
					

prints

QML MyCustomType (unknown location): property cannot be set to 0
					

该函数在 Qt 5.9 引入。

另请参阅 QtQml::qmlDebug and QtQml::qmlInfo .

宏文档编制

QML_DECLARE_TYPE ()

相当于 Q_DECLARE_METATYPE(TYPE *) and Q_DECLARE_METATYPE(QQmlListProperty<TYPE>)

QML_DECLARE_TYPEINFO ( Type , Flags )

声明额外特性为给定 Type 如描述通过指定 Flags .

Current the only supported type info is QML_HAS_ATTACHED_PROPERTIES which declares that the Type supports attached properties .