QQmlEngine 类

QQmlEngine 类提供实例化 QML 组件的环境。 更多...

头: #include <QQmlEngine>
CMake: find_package(Qt6 REQUIRED COMPONENTS Qml)
target_link_libraries(mytarget PRIVATE Qt6::Qml)
qmake: QT += qml
继承: QJSEngine
继承者:

QQmlApplicationEngine

特性

公共函数

QQmlEngine (QObject * parent = nullptr)
virtual ~QQmlEngine () override
void addImageProvider (const QString & providerId , QQmlImageProviderBase * provider )
void addImportPath (const QString & path )
void addPluginPath (const QString & path )
void addUrlInterceptor (QQmlAbstractUrlInterceptor * urlInterceptor )
QUrl baseUrl () const
void clearComponentCache ()
void clearSingletons ()
QQmlImageProviderBase * imageProvider (const QString & providerId ) const
QStringList importPathList () const
QQmlIncubationController * incubationController () const
QUrl interceptUrl (const QUrl & url , QQmlAbstractUrlInterceptor::DataType type ) const
(从 6.6 起) void markCurrentFunctionAsTranslationBinding ()
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 )
void removeUrlInterceptor (QQmlAbstractUrlInterceptor * urlInterceptor )
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 )
T singletonInstance (int qmlTypeId )
(从 6.5 起) T singletonInstance (QAnyStringView uri , QAnyStringView typeName )
void trimComponentCache ()
QList<QQmlAbstractUrlInterceptor *> urlInterceptors () const

公共槽

void retranslate ()

信号

void exit (int retCode )
(从 6.5 起) void offlineStoragePathChanged ()
void quit ()
void warnings (const QList<QQmlError> & warnings )

静态公共成员

QQmlContext * contextForObject (const QObject * object )
void setContextForObject (QObject * object , QQmlContext * context )

重实现保护函数

virtual bool event (QEvent * e ) override
enum QQmlModuleImportSpecialVersions { QQmlModuleImportModuleAny, QQmlModuleImportLatest, QQmlModuleImportAuto }
QObject * qmlAttachedPropertiesObject (const QObject * attachee , bool create = true)
void qmlClearTypeRegistrations ()
QQmlContext * qmlContext (const QObject * object )
QQmlEngine * qmlEngine (const QObject * object )
bool qmlProtectModule (const char * uri , int majVersion )
int qmlRegisterAnonymousType (const char * uri , int versionMajor )
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 )
void qmlRegisterModule (const char * uri , int versionMajor , int versionMinor )
void qmlRegisterModuleImport (const char * uri , int moduleMajor , const char * import , int importMajor = QQmlModuleImportLatest, int importMinor = QQmlModuleImportLatest)
int qmlRegisterRevision (const char * uri , int versionMajor , int versionMinor )
int qmlRegisterSingletonInstance (const char * uri , int versionMajor , int versionMinor , const char * typeName , QObject * cppObject )
int qmlRegisterSingletonType (const char * uri , int versionMajor , int versionMinor , const char * typeName , std::function<QJSValue (QQmlEngine *, QJSEngine *)> callback )
int qmlRegisterSingletonType (const char * uri , int versionMajor , int versionMinor , const char * typeName , std::function<QObject *(QQmlEngine *, QJSEngine *)> callback )
int qmlRegisterSingletonType (const QUrl & url , const char * uri , int versionMajor , int versionMinor , const char * qmlName )
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 )
int qmlTypeId (const char * uri , int versionMajor , int versionMinor , const char * qmlName )
void qmlUnregisterModuleImport (const char * uri , int moduleMajor , const char * import , int importMajor = QQmlModuleImportLatest, int importMinor = QQmlModuleImportLatest)

QML_ADDED_IN_VERSION ( MAJOR , MINOR )
QML_ANONYMOUS
QML_ATTACHED ( ATTACHED_TYPE )
(从 6.5 起) QML_CONSTRUCTIBLE_VALUE
QML_DECLARE_TYPE
QML_DECLARE_TYPEINFO ( Type , Flags )
QML_ELEMENT
QML_EXTENDED ( EXTENDED_TYPE )
QML_EXTENDED_NAMESPACE ( EXTENDED_NAMESPACE )
QML_EXTRA_VERSION ( MAJOR , MINOR )
QML_FOREIGN ( FOREIGN_TYPE )
QML_FOREIGN_NAMESPACE ( FOREIGN_NAMESPACE )
QML_IMPLEMENTS_INTERFACES ( interfaces )
QML_INTERFACE
QML_NAMED_ELEMENT ( name )
QML_REMOVED_IN_VERSION ( MAJOR , MINOR )
QML_SEQUENTIAL_CONTAINER ( VALUE_TYPE )
QML_SINGLETON
(从 6.5 起) QML_STRUCTURED_VALUE
QML_UNAVAILABLE
QML_UNCREATABLE ( reason )
QML_VALUE_TYPE ( name )

详细描述

A QQmlEngine is used to manage components and objects created from them and execute their bindings and functions. QQmlEngine also inherits from QJSEngine which allows seamless integration between your QML components and JavaScript code.

每个 QML 组件被实例化在 QQmlContext . In QML, contexts are arranged hierarchically and this hierarchy is managed by the QQmlEngine. By default, components are instantiated in the 根上下文 .

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

特性文档编制

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 openDatabaseSync() 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 )

通知程序信号:

void offlineStoragePathChanged ()

另请参阅 Qt Quick 本地存储 QML 类型 .

成员函数文档编制

[explicit] QQmlEngine:: QQmlEngine ( QObject * parent = nullptr)

创建新 QQmlEngine 采用给定 parent .

[override virtual noexcept] QQmlEngine:: ~QQmlEngine ()

销毁 QQmlEngine .

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

See ~ QJSEngine () 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 模块 ,和 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 ().

void QQmlEngine:: addUrlInterceptor ( QQmlAbstractUrlInterceptor * urlInterceptor )

添加 urlInterceptor to be used when resolving URLs in QML. This also applies to URLs used for loading script files and QML types. The URL interceptors should not be modifed while the engine is loading files, or URL selection may be inconsistent. Multiple URL interceptors, when given, will be called in the order they were added for each URL.

QQmlEngine does not take ownership of the interceptor and won't delete it.

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.

注意: Any existing objects created from QML components retain their types, even if you clear the component cache. This includes singleton objects. If you create more objects from the same QML code after clearing the cache, the new objects will be of different types than the old ones. Assigning such a new object to a property of its declared type belonging to an object created before clearing the cache won't work.

As a general rule of thumb, make sure that no objects created from QML components are alive when you clear the component cache.

另请参阅 trimComponentCache () 和 clearSingletons ().

void QQmlEngine:: clearSingletons ()

Clears all singletons the engine owns.

This function drops all singleton instances, deleting any QObjects owned by the engine among them. This is useful to make sure that no QML-created objects are left before calling clearComponentCache ().

QML properties holding QObject -based singleton instances become null if the engine owns the singleton or retain their value if the engine doesn't own it. The singletons are not automatically re-created by accessing existing QML-created objects. Only when new components are instantiated, the singletons are re-created.

另请参阅 clearComponentCache ().

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

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

QQmlEngine instantiates a QObject , an internal context is assigned to it automatically. Such internal contexts are read-only. You cannot set context properties on them.

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

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

重实现: QObject::event (QEvent *e).

[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 .

另请参阅 quit ().

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

Returns the image provider set for providerId if found; otherwise returns nullptr .

另请参阅 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, this list contains the paths mentioned in QML 导入路径 .

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

QQmlIncubationController *QQmlEngine:: incubationController () const

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

另请参阅 setIncubationController ().

QUrl QQmlEngine:: interceptUrl (const QUrl & url , QQmlAbstractUrlInterceptor::DataType type ) const

Run the current URL interceptors on the given url 为给定 type 并返回结果。

[since 6.6] void QQmlEngine:: markCurrentFunctionAsTranslationBinding ()

If this method is called inside of a function that is part of a binding in QML, the binding will be treated as a translation binding.

class I18nAwareClass : public QObject {
  //...
   QString text() const
   {
        if (auto engine = qmlEngine(this))
            engine->markCurrentFunctionAsTranslationBinding();
        return tr("Hello, world!");
   }
};
					

注意: This function is mostly useful if you wish to provide your own alternative to the qsTr function. To ensure that properties exposed from C++ classes are updated on language changes, it is instead recommended to react to LanguageChange events. That is a more general mechanism which also works when the class is used in a non-QML context, and has slightly less overhead. However, using markCurrentFunctionAsTranslationBinding can be acceptable when the class is already closely tied to the QML engine. For more details, see 为动态语言改变做准备

该函数在 Qt 6.6 引入。

另请参阅 QQmlEngine::retranslate .

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 ().

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

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

另请参阅 LocalStorage.openDatabaseSync() .

[signal, since 6.5] void QQmlEngine:: offlineStoragePathChanged ()

此信号发射当 offlineStoragePath 改变。

注意: 通知程序信号对于特性 offlineStoragePath .

该函数在 Qt 6.5 引入。

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 .

void QQmlEngine:: removeUrlInterceptor ( QQmlAbstractUrlInterceptor * urlInterceptor )

Remove a urlInterceptor that was previously added using addUrlInterceptor . The URL interceptors should not be modifed while the engine is loading files, or URL selection may be inconsistent.

This does not delete the interceptor, but merely removes it from the engine. You can re-use it on the same or a different engine afterwards.

[slot] void QQmlEngine:: retranslate ()

Refreshes all binding expressions that use strings marked for translation.

Call this function after you have installed a new translator with QCoreApplication::installTranslator , to ensure that your user-interface shows up-to-date translations.

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, this list contains the paths mentioned in QML 导入路径 .

警告: Calling setImportPathList does not preserve the default import paths.

另请参阅 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.

注意: QQmlEngine does not take ownership of the factory.

另请参阅 networkAccessManagerFactory ().

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 ().

template <typename T> T QQmlEngine:: singletonInstance ( int qmlTypeId )

Returns the instance of a singleton type that was registered under qmlTypeId .

The template argument T may be either QJSValue or a pointer to a QObject -derived type and depends on how the singleton was registered. If no instance of T has been created yet, it is created now. If qmlTypeId does not represent a valid singleton type, either a default constructed QJSValue nullptr 被返回。

QObject * example:

class MySingleton : public QObject {
    Q_OBJECT
    // Register as default constructed singleton.
    QML_ELEMENT
    QML_SINGLETON
    static int typeId;
    // ...
};
    MySingleton::typeId = qmlTypeId(...);
    // Retrieve as QObject*
    QQmlEngine engine;
    MySingleton* instance = engine.singletonInstance<MySingleton*>(MySingleton::typeId);
					

QJSValue 范例:

    // Register with QJSValue callback
    int typeId = qmlRegisterSingletonType(...);
    // Retrieve as QJSValue
    QQmlEngine engine;
    QJSValue instance = engine.singletonInstance<QJSValue>(typeId);
					

It is recommended to store the QML type id, e.g. as a static member in the singleton class. The lookup via qmlTypeId () is costly.

另请参阅 QML_SINGLETON , qmlRegisterSingletonType (),和 qmlTypeId ().

[since 6.5] template <typename T> T QQmlEngine:: singletonInstance ( QAnyStringView uri , QAnyStringView typeName )

这是重载函数。

Returns the instance of a singleton type named typeName from the module specified by uri .

This method can be used as an alternative to calling qmlTypeId followed by the id based overload of singletonInstance. This is convenient when one only needs to do a one time setup of a singleton; if repeated access to the singleton is required, caching its typeId will allow faster subsequent access via the type-id based overload .

The template argument T may be either QJSValue or a pointer to a QObject -derived type and depends on how the singleton was registered. If no instance of T has been created yet, it is created now. If typeName does not represent a valid singleton type, either a default constructed QJSValue nullptr 被返回。

    QQmlEngine engine;
    MySingleton *singleton = engine.singletonInstance<MySingleton *>("mymodule", "MySingleton");
/
					

该函数在 Qt 6.5 引入。

另请参阅 QML_SINGLETON , qmlRegisterSingletonType (),和 qmlTypeId ().

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 ().

QList < QQmlAbstractUrlInterceptor *> QQmlEngine:: urlInterceptors () const

Returns the list of currently active URL interceptors.

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

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

相关非成员

enum QQmlModuleImportSpecialVersions

Defines some special values that can be passed to the version arguments of qmlRegisterModuleImport () 和 qmlUnregisterModuleImport ().

常量 描述
QQmlEngine::QQmlModuleImportModuleAny -1 When passed as majorVersion of the base module, signifies that the import is to be applied to any version of the module.
QQmlEngine::QQmlModuleImportLatest -1 When passed as major or minor version of the imported module, signifies that the latest overall, or latest minor version of a specified major version shall be imported.
QQmlEngine::QQmlModuleImportAuto -2 When passed as major version of the imported module, signifies that the version of the base module shall be forwarded.

template <typename T> 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.

返回 nullptr 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 .

另请参阅 QML_ATTACHED () 和 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 ().

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 ().

bool qmlProtectModule (const char * uri , int majVersion )

This function protects a module from further modification. 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.

Once qmlProtectModule has been called, a QML engine will not search for a new qmldir file to load the module anymore. It will re-use any qmldir files it has loaded before, though. Therefore, types present at this point continue to work. Mind that different QML engines may load different modules. The module protection, however, is global and affects all engines. The overhead of locating qmldir files and loading plugins may be noticeable with slow file systems. Therefore, protecting a module once you are sure you won't need to load it anymore can be a good optimization. Mind also that the module lock not only affects plugins but also any other qmldir directives, like import or prefer , as well as any composite types or scripts declared in a qmldir 文件。

In addition, after this function is called, any attempt to register C++ types into this uri, major version combination will lead to a runtime error.

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.

template <typename T> int qmlRegisterAnonymousType (const char * uri , int versionMajor )

This template function registers the C++ type in the QML system as an anonymous type. The resulting QML type does not have a name. Therefore, instances of this type cannot be created from the QML system. You can, however, access instances of the type when they are exposed as properties of other types.

Use this function when the type will not be referenced by name, specifically for C++ types that are used on the left-hand side of a property binding. To indicate to which module the type belongs use uri and versionMajor .

For example, consider the following two classes:

class Bar : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString baz READ baz WRITE setBaz NOTIFY bazChanged)
public:
    Bar() {}
    QString baz() const { return mBaz; }
    void setBaz(const QString &baz)
    {
        if (baz == mBaz)
            return;
        mBaz = baz;
        emit bazChanged();
    }
signals:
    void bazChanged();
private:
    QString mBaz;
};
class Foo : public QObject
{
    Q_OBJECT
    Q_PROPERTY(Bar *bar READ bar CONSTANT FINAL)
public:
    Foo() {}
    Bar *bar() { return &mBar; }
private:
    Bar mBar;
};
					

In QML, we assign a string to the baz property of bar :

Foo {
    bar.baz: "abc"
    Component.onCompleted: print(bar.baz)
}
					

For the QML engine to know that the Bar 类型拥有 baz property, we have to make Bar known:

qmlRegisterType<Foo>("App", 1, 0, "Foo");
qmlRegisterAnonymousType<Bar>("App", 1);
					

As the Foo type is instantiated in QML, it must be registered with the version of qmlRegisterType () that takes an element name.

返回 QML 类型 ID。

另请参阅 QML_ANONYMOUS and Choosing the Correct Integration Method Between C++ and QML .

template <typename T, typename E> 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。

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

template <typename T, typename E> 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。

另请参阅 QML_EXTENDED (), QML_UNCREATABLE (),和 qmlRegisterUncreatableType ().

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.

void qmlRegisterModuleImport (const char * uri , int moduleMajor , const char * import , int importMajor = QQmlModuleImportLatest, int importMinor = QQmlModuleImportLatest)

Registers a qmldir-import for module uri of major version moduleMajor .

This has the same effect as an import statement in a qmldir file: Whenever uri of version moduleMajor is imported, import of version importMajor . importMinor is automatically imported, too. If importMajor is QQmlModuleImportLatest the latest version available of that module is imported, and importMinor does not matter. If importMinor is QQmlModuleImportLatest the latest minor version of a importMajor is chosen. If importMajor is QQmlModuleImportAuto the version of import is version of uri being imported, and importMinor does not matter. If moduleMajor is QQmlModuleImportModuleAny the module import is applied for any major version of uri . For example, you may specify that whenever any version of MyModule is imported, the latest version of MyOtherModule should be imported. Then, the following call would be appropriate:

qmlRegisterModuleImport("MyModule", QQmlModuleImportModuleAny,
                        "MyOtherModule", QQmlModuleImportLatest);
					

Or, you may specify that whenever major version 5 of "MyModule" is imported, then version 3.14 of "MyOtherModule" should be imported:

qmlRegisterModuleImport("MyModule", 5, "MyOtherModule", 3, 14);
					

Finally, if you always want the same version of "MyOtherModule" to be imported whenever "MyModule" is imported, specify the following:

qmlRegisterModuleImport("MyModule", QQmlModuleImportModuleAny,
                        "MyOtherModule", QQmlModuleImportAuto);
					

另请参阅 qmlUnregisterModuleImport ().

template <typename T, int metaObjectRevision> 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 qmlRegisterSingletonInstance (const char * uri , int versionMajor , int versionMinor , const char * typeName , QObject * cppObject )

This function is used to register a singleton object cppObject , with a particular uri and typeName . Its version is a combination of versionMajor and versionMinor .

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

Use this function to register an object 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; in turn this type name may be used as the target in a Connections type, or like any other type ID. However, there's one exception: a QObject singleton type property can't be aliased because the singleton type name does not identify an object within the same component as any other item.

注意: cppObject must outlive the QML engine in which it is used. Moreover, cppObject must have the same thread affinity as the engine. If you want separate singleton instances for multiple engines, you need to use qmlRegisterSingletonType 。见 线程和 QObject for more information about thread safety.

NOTE: qmlRegisterSingleton can only be used when all types of that module are registered procedurally.

用法:

// 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:
    explicit SingletonTypeExample(QObject* parent = nullptr) : QObject(parent) {}
    Q_INVOKABLE int doSomething()
    {
        setSomeProperty(5);
        return m_someProperty;
    }
    int someProperty() const { return m_someProperty; }
    void setSomeProperty(int val) {
        if (m_someProperty != val) {
            m_someProperty = val;
            emit somePropertyChanged(val);
        }
    }
signals:
    void somePropertyChanged(int newValue);
private:
    int m_someProperty = 0;
};
					
// Second, create an instance of the object
// allocate example before the engine to ensure that it outlives it
QScopedPointer<SingletonTypeExample> example(new SingletonTypeExample);
QQmlEngine engine;
// Third, register the singleton type provider with QML by calling this
// function in an initialization function.
qmlRegisterSingletonInstance("Qt.example.qobjectSingleton", 1, 0, "MyApi", example.get());
					

In order to use the registered singleton type in QML, you must import the URI with the corresponding version.

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

另请参阅 QML_SINGLETON and qmlRegisterSingletonType .

int qmlRegisterSingletonType (const char * uri , int versionMajor , int versionMinor , const char * typeName , std::function < 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
}
					

另请参阅 QML_SINGLETON and Choosing the Correct Integration Method Between C++ and QML .

template <typename T> int qmlRegisterSingletonType (const char * uri , int versionMajor , int versionMinor , const char * typeName , std::function < 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.

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 flag set.

用法:

// 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 = nullptr)
        : 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.qobjectSingleton", 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()
    }
}
					

另请参阅 QML_SINGLETON and Choosing the Correct Integration Method Between C++ and QML .

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.

另请参阅 QML_SINGLETON .

template <typename T> 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.

另请参阅 QML_ELEMENT , QML_NAMED_ELEMENT (),和 Choosing the Correct Integration Method Between C++ and QML .

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.

另请参阅 QML_UNAVAILABLE , qmlRegisterUncreatableType (),和 Choosing the Correct Integration Method Between C++ and QML .

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_ENUM_NS(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)
					

另请参阅 QML_ELEMENT , QML_NAMED_ELEMENT (),和 QML_UNCREATABLE ().

template <typename T> 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。

另请参阅 QML_UNCREATABLE (), qmlRegisterTypeNotAvailable (),和 Choosing the Correct Integration Method Between C++ and QML .

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

Returns the QML type id of a type that was registered with the name qmlName in a particular uri and a version specified in versionMajor and versionMinor .

This function returns the same value as the QML type registration functions such as qmlRegisterType () 和 qmlRegisterSingletonType ().

qmlName , uri and versionMajor match a registered type, but the specified minor version in versionMinor is higher, then the id of the type with the closest minor version is returned.

Returns -1 if no matching type was found or one of the given parameters was invalid.

另请参阅 QML_ELEMENT , QML_NAMED_ELEMENT , QML_SINGLETON , qmlRegisterType (),和 qmlRegisterSingletonType ().

void qmlUnregisterModuleImport (const char * uri , int moduleMajor , const char * import , int importMajor = QQmlModuleImportLatest, int importMinor = QQmlModuleImportLatest)

Removes a module import previously registered with qmlRegisterModuleImport ()

Calling this function makes sure that import of version importMajor . importMinor is not automatically imported anymore when uri of version moduleMajor is. The version resolution works the same way as with qmlRegisterModuleImport ().

另请参阅 qmlRegisterModuleImport ().

宏文档编制

QML_ADDED_IN_VERSION ( MAJOR , MINOR )

Declares that the enclosing type or namespace was added in the specified MAJOR . MINOR version. The version is assumed to be in line with any revisions given by Q_REVISION () macros on methods, slots, or signals, and any REVISION() attributes on properties declared with Q_PROPERTY ().

QML_ADDED_IN_VERSION() only takes effect if the type or namespace is available in QML, by having a QML_ELEMENT , QML_NAMED_ELEMENT (), QML_ANONYMOUS ,或 QML_INTERFACE 宏。

If the QML module the type belongs to is imported with a lower version than the one determined this way, the QML type is invisible.

另请参阅 QML_ELEMENT and QML_NAMED_ELEMENT .

QML_ANONYMOUS

Declares the enclosing type to be available, but anonymous in QML. The type cannot be created or used to declare properties in QML, but when passed from C++, it is recognized. In QML, you can use properties of this type if they are declared in C++.

另请参阅 QML_ELEMENT , QML_NAMED_ELEMENT (), QML_UNCREATABLE (),和 QML_INTERFACE .

QML_ATTACHED ( ATTACHED_TYPE )

Declares that the enclosing type attaches ATTACHED_TYPE as an attached property to other types. This takes effect if the type is exposed to QML using a QML_ELEMENT or QML_NAMED_ELEMENT () 宏。

注意: The class name needs to be fully qualified, even if you're already inside the namespace.

另请参阅 QML_ELEMENT , QML_NAMED_ELEMENT (), qmlAttachedPropertiesObject (),和 Providing Attached Properties .

[since 6.5] QML_CONSTRUCTIBLE_VALUE

Marks the surrounding value type as constructible. That is, any Q_INVOKABLE constructors of the type that take exactly one argument can be used when assigning a JavaScript value to a property of this type.

可以声明的可构造值类型如下:

class MyValueType
{
    Q_GADGET
    QML_VALUE_TYPE(myValueType)
    QML_CONSTRUCTIBLE_VALUE
public:
    Q_INVOKABLE MyValueType(double d);
    // ...
};
					

With the above type, the following QML code will produce a MyValueType value using the given constructor and assign it to the property.

QtObject {
    property myValueType v: 5.4
}
					

You can also construct lists of values this way:

QtObject {
    property list<myValueType> v: [5.4, 4.5, 3.3]
}
					

If you make value types addressable , you can use such a type in a type assertion to explicitly construct it:

pragma ValueTypeBehavior: Addressable
QtObject {
    function process(d: real) {
        let v = d as myValueType;
        // v is a myValueType now, not a number
    }
}
					

该宏在 Qt 6.5 引入。

另请参阅 QML_VALUE_TYPE .

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 . QML_DECLARE_TYPEINFO() is not necessary if Type 包含 QML_ATTACHED 宏。

QML_ELEMENT

Declares the enclosing type or namespace to be available in QML, using its class or namespace name as the QML element name.

For example, this makes the C++ class Slider available as a QML type named Slider . All its properties, invokable methods and enums are exposed.

class Slider : public QObject
{
    Q_OBJECT
    QML_ELEMENT
    Q_PROPERTY(int value READ value WRITE setValue NOTIFY valueChanged FINAL)
    // ...
public:
    enum Slippiness {
        Dry, Wet, Icy
    };
    Q_ENUM(Slippiness)
    Q_INVOKABLE void slide(Slippiness slippiness);
    // ...
}
					

You can use the build system to register the type in the type namespace com.mycompany.qmlcomponents with major version 1 . For qmake, specify the following in your project file:

CONFIG += qmltypes
QML_IMPORT_NAME = com.mycompany.qmlcomponents
QML_IMPORT_MAJOR_VERSION = 1
					

With CMake, you pass the URI and version to qt_add_qml_module

qt6_add_qml_module(myapp
  URI com.mycompany.qmlcomponents
  VERSION 1.0
)
					

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

import com.mycompany.qmlcomponents 1.0
Slider {
    value: 12
    Component.onCompleted: slide(Slider.Icy)
    // ...
}
					

You can also make namespaces tagged with Q_NAMESPACE available this way, in order to expose any enums tagged with Q_ENUM_NS they contain:

namespace MyNamespace {
  Q_NAMESPACE
  QML_ELEMENT
  enum MyEnum {
      Key1,
      Key2,
  };
  Q_ENUM_NS(MyEnum)
}
					

In QML, you can then use the enums:

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

NOTE: When classes have the same name but are located in different namespaces using QML_ELEMENT on both of them will cause a conflict. Make sure to use QML_NAMED_ELEMENT () for one of them instead.

注意: The class name needs to be fully qualified, even if you're already inside the namespace.

另请参阅 Choosing the Correct Integration Method Between C++ and QML , QML_NAMED_ELEMENT (), Q_REVISION (),和 QML_ADDED_IN_VERSION ().

QML_EXTENDED ( EXTENDED_TYPE )

Declares that the enclosing type uses EXTENDED_TYPE as an extension to provide further properties, methods, and enumerations in QML. This takes effect if the type is exposed to QML using a QML_ELEMENT or QML_NAMED_ELEMENT () 宏。

警告: Members of EXTENDED_TYPE are implicitly treated as FINAL.

注意: The class name needs to be fully qualified, even if you're already inside the namespace.

另请参阅 QML_ELEMENT , QML_NAMED_ELEMENT (), QML_EXTENDED_NAMESPACE (),和 Registering Extension Objects .

QML_EXTENDED_NAMESPACE ( EXTENDED_NAMESPACE )

Declares that the enclosing type uses EXTENDED_NAMESPACE as an extension to provide further enumerations in QML. This takes effect if the type is exposed to QML using a QML_ELEMENT or QML_NAMED_ELEMENT () macro. The enumerations need to be exposed to the metaobject system for this to work.

For example, give the following C++ code

namespace MyNamespace {
    Q_NAMESPACE
    enum MyEnum { MyEnumerator = 10 };
    Q_ENUM_NS(MyEnum)
}
class QmlType : public QObject
{
    Q_OBJECT
    QML_ELEMENT
    QML_EXTENDED_NAMESPACE(MyNamespace)
}
					

we can access the enum in QML:

QmlType {
    property int i: QmlType.MyEnumerator // i will be 10
}
					

注意: EXTENDED_NAMESPACE can also be a QObject or QGadget; in that case - and in contrast to QML_EXTENDED , which also exposes methods and properties - only its enumerations are exposed.

注意: EXTENDED_NAMESPACE must have a metaobject; i.e. it must either be a namespace which contains the Q_NAMESPACE macro or a QObject /QGadget.

注意: The class name needs to be fully qualified, even if you're already inside the namespace.

另请参阅 QML_ELEMENT , QML_NAMED_ELEMENT (), QML_EXTENDED (), Registering Extension Objects , Q_ENUM ,和 Q_ENUM_NS .

QML_EXTRA_VERSION ( MAJOR , MINOR )

Declare that the type should also be available in version MAJOR . MINOR . This can be helpful if a type should be available in multiple major versions.

Types are automatically registered for:

Notably, they are not automatically registered in any PAST_MAJOR_VERSIONS between the above. You can use QML_EXTRA_VERSION to manually register your types in further major versions.

注意: Keeping multiple PAST_MAJOR_VERSIONS around is computationally expensive.

另请参阅 QML_ELEMENT and QML_ADDED_IN_VERSION .

QML_FOREIGN ( FOREIGN_TYPE )

Declares that any QML_ELEMENT , QML_NAMED_ELEMENT (), QML_ANONYMOUS , QML_INTERFACE , QML_UNCREATABLE (), QML_SINGLETON , QML_ADDED_IN_VERSION (), QML_REMOVED_IN_VERSION (), QML_ADDED_IN_MINOR_VERSION (), QML_REMOVED_IN_MINOR_VERSION (), QML_EXTENDED (),或 QML_EXTENDED_NAMESPACE () macros in the enclosing C++ type do not apply to the enclosing type but instead to FOREIGN_TYPE . The enclosing type still needs to be registered with the 元对象系统 使用 Q_GADGET or Q_OBJECT 宏。

This is useful for registering types that cannot be amended to add the macros, for example because they belong to 3rdparty libraries. To register a namespace, see QML_FOREIGN_NAMESPACE ().

注意: You may want to use QML_NAMED_ELEMENT () 而不是 QML_ELEMENT 。采用 QML_ELEMENT , the element is named after the struct it is contained in, not the foreign type. The Foreign objects integration chapter in Writing advanced QML Extensions with C++ demonstrates this.

注意: QML_ATTACHED () can currently not be redirected like this. It has to be specificed in the same type that implements qmlAttachedProperties().

注意: The class name needs to be fully qualified, even if you're already inside the namespace.

另请参阅 QML_ELEMENT , QML_NAMED_ELEMENT (),和 QML_FOREIGN_NAMESPACE ().

QML_FOREIGN_NAMESPACE ( FOREIGN_NAMESPACE )

Declares that any QML_ELEMENT , QML_NAMED_ELEMENT (), QML_ANONYMOUS , QML_INTERFACE , QML_UNCREATABLE (), QML_SINGLETON , QML_ADDED_IN_VERSION (), QML_REMOVED_IN_VERSION (), QML_ADDED_IN_MINOR_VERSION (),或 QML_REMOVED_IN_MINOR_VERSION () macros in the enclosing C++ namespace do not apply to the enclosing type but instead to FOREIGN_NAMESPACE . The enclosing namespace still needs to be registered with the 元对象系统 使用 Q_NAMESPACE 宏。

This is useful for registering namespaces that cannot be amended to add the macros, for example because they belong to 3rdparty libraries.

另请参阅 QML_ELEMENT , QML_NAMED_ELEMENT (),和 QML_FOREIGN ().

QML_IMPLEMENTS_INTERFACES ( interfaces )

This macro tells Qt which QML interfaces the class implements. This macro should only be used for interfacing with classes using QML_INTERFACE ,使用 Q_INTERFACES otherwise. It's required in order for declarative registration via QML_ELEMENT to function properly.

另请参阅 QML_INTERFACE and Q_INTERFACES .

QML_INTERFACE

This macro registers the enclosing C++ type in the QML system as an interface.

Types registered as an interface in QML should also declare themselves as an interface with the 元对象系统 。例如:

struct FooInterface
{
    QML_INTERFACE
public:
    virtual ~FooInterface();
    virtual void doSomething() = 0;
};
Q_DECLARE_INTERFACE(FooInterface, "org.foo.FooInterface")
					

When registered with QML in this way, they can be used as property types:

Q_PROPERTY (FooInterface *foo READ foo WRITE setFoo)

When you assign a QObject sub-class to this property, the QML engine does the interface cast to FooInterface* automatically.

Interface types are implicitly anonymous and uncreatable in QML.

NOTE: When inheriting from types using QML_INTERFACE, use QML_IMPLEMENTS_INTERFACES 而不是 Q_INTERFACES .

另请参阅 QML_IMPLEMENTS_INTERFACES (), QML_ELEMENT , QML_NAMED_ELEMENT (), QML_UNCREATABLE (),和 QML_ANONYMOUS .

QML_NAMED_ELEMENT ( name )

Declares the enclosing type or namespace to be available in QML, using name as the element name. Otherwise behaves the same as QML_ELEMENT .

class SqlEventDatabase : public QObject
{
    Q_OBJECT
    QML_NAMED_ELEMENT(EventDatabase)
    // ...
};
					

另请参阅 Choosing the Correct Integration Method Between C++ and QML and QML_ELEMENT .

QML_REMOVED_IN_VERSION ( MAJOR , MINOR )

Declares that the enclosing type or namespace was removed in the specified MAJOR . MINOR version. This is primarily useful when replacing the implementation of a QML type. If a corresponding QML_ADDED_IN_VERSION () is present on a different type or namespace of the same QML name, then the removed type is used when importing versions of the module lower than MAJOR . MINOR , and the added type is used when importing versions of the module greater or equal MAJOR . MINOR .

QML_REMOVED_IN_VERSION() only takes effect if type or namespace is available in QML, by having a QML_ELEMENT , QML_NAMED_ELEMENT (), QML_ANONYMOUS ,或 QML_INTERFACE 宏。

另请参阅 QML_ELEMENT and QML_NAMED_ELEMENT .

QML_SEQUENTIAL_CONTAINER ( VALUE_TYPE )

This macro declares the enclosing or referenced type as a sequential container managing a sequence of VALUE_TYPE 元素。 VALUE_TYPE can be an actual 值类型 or a pointer to an 对象类型 . You will rarely be able to add this macro to the actual container declaration since containers are usually templates. You should use QML_FOREIGN to attach the type registration to a template instantiation. Using this technique you can, for example, declare sequential containers like this:

class IntDequeRegistration
{
  Q_GADGET
  QML_FOREIGN(std::deque<int>)
  QML_ANONYMOUS
  QML_SEQUENTIAL_CONTAINER(int)
};
					

After this, you can use the container like a JavaScript array in QML.

class Maze
{
  Q_OBJECT
  Q_ELEMENT
  // 0: North, 1: East, 2: South, 3: West
  Q_PROPERTY(std::deque<int> solution READ solution CONSTANT FINAL)
  [...]
}
					
Item {
  Maze {
    id: maze
  }
  function showSolution() {
      maze.solution.forEach([...])
  }
}
					

注意: For QML 值类型 QList is automatically registered as sequential container. For QML 对象类型 QQmlListProperty is. You don't have to add these registrations.

注意: You cannot currently give the container a custom name. Any argument passed to QML_NAMED_ELEMENT is ignored. The automatically registered sequential containers are available under the familiar list<...> names, for example list< QtObject > or list<font> .

注意: The class name needs to be fully qualified, even if you're already inside the namespace.

另请参阅 QML_ANONYMOUS and QML_FOREIGN ().

QML_SINGLETON

Declares the enclosing type to be a singleton in QML. This only takes effect if the type is a Q_OBJECT and is available in QML (by having a QML_ELEMENT or QML_NAMED_ELEMENT () macro). By default, each QQmlEngine will try to create a singleton instance using either the type's default constructor or a static factory function of the signature T *create(QQmlEngine *, QJSEngine *) when the type is first accessed. If both do exist and are accessible, the default constructor is preferred. If there is no default constructor and no factory function the singleton is inaccessible. The QML engine generally assumes ownership of the singleton and will delete it when the engine itself is destroyed. You can prevent this by calling QJSEngine::setObjectOwnership () on the singleton.

In order to declare a default-constructible class as singleton, all you have to do is add QML_SINGLETON:

class MySingleton : public QObject
{
    Q_OBJECT
    QML_ELEMENT
    QML_SINGLETON
    // Q_PROPERTY( ... )
public:
    // members, Q_INVOKABLE functions, etc.
};
					

If the singleton class is not default-constructible, but you can modify it, you can add a factory function to it, in order to make it accessible:

class MySingleton : public QObject
{
    Q_OBJECT
    QML_ELEMENT
    QML_SINGLETON
    // Q_PROPERTY( ... )
public:
    static MySingleton *create(QQmlEngine *qmlEngine, QJSEngine *jsEngine)
    {
        MySingleton *result = nullptr;
        // Create the object using some custom constructor or factory.
        // The QML engine will assume ownership and delete it, eventually.
        return result;
    }
    // members, Q_INVOKABLE functions, etc
};
					

If you cannot modify the class and it does not have a default constructor or a suitable factory function, you can provide a QML_FOREIGN wrapper to define the factory function:

struct SingletonForeign
{
    Q_GADGET
    QML_FOREIGN(MySingleton)
    QML_SINGLETON
    QML_NAMED_ELEMENT(MySingleton)
public:
    static MySingleton *create(QQmlEngine *, QJSEngine *engine)
    {
        MySingleton *result = nullptr;
        // Create the instance using some custom constructor or factory.
        // The QML engine will assume ownership and delete it, eventually.
        return result;
    }
};
					

Finally, if you want to provide one specific singleton object, the creation of which you cannot control, you can return that from a factory function. This is a replacement for the qmlRegisterSingletonInstance function. If you were calling

qmlRegisterSingletonInstance("MyModule", 1, 0, "MySingleton", myObject);
					

with myObject being of type MySingleton * , you can do the following instead:

struct SingletonForeign
{
    Q_GADGET
    QML_FOREIGN(MySingleton)
    QML_SINGLETON
    QML_NAMED_ELEMENT(MySingleton)
public:
    // Initialize this using myObject where you would previously
    // call qmlRegisterSingletonInstance().
    inline static MySingleton *s_singletonInstance = nullptr;
    static MySingleton *create(QQmlEngine *, QJSEngine *engine)
    {
        // The instance has to exist before it is used. We cannot replace it.
        Q_ASSERT(s_singletonInstance);
        // The engine has to have the same thread affinity as the singleton.
        Q_ASSERT(engine->thread() == s_singletonInstance->thread());
        // There can only be one engine accessing the singleton.
        if (s_engine)
            Q_ASSERT(engine == s_engine);
        else
            s_engine = engine;
        // Explicitly specify C++ ownership so that the engine doesn't delete
        // the instance.
        QJSEngine::setObjectOwnership(s_singletonInstance,
                                      QJSEngine::CppOwnership);
        return s_singletonInstance;
    }
private:
    inline static QJSEngine *s_engine = nullptr;
};
					

This way, the pre-existing class MySingleton is declared to be a QML singleton, called MySingleton . You can specify an instance for it any time before it is used by setting the s_singletonInstance member. None of this requires modification of MySingleton 本身。

注意: This pattern doesn't work if either the singleton is accessed by multiple QML engines, or if the QML engine accessing it has a different thread affinity than the singleton object itself. As shown above, you can check the parameters to the create() method for identity and thread affinity of the engine in order to assert on that.

另请参阅 QML_ELEMENT , QML_NAMED_ELEMENT (), qmlRegisterSingletonInstance (), QQmlEngine::singletonInstance (),和 QML 单例 .

[since 6.5] QML_STRUCTURED_VALUE

Marks the surrounding value type as structured. Structured value types can and will preferably be constructed property-by-property from a JavaScript object. A structured value type, however is always QML_CONSTRUCTIBLE_VALUE , too. This means, you can still provide Q_INVOKABLE constructors in order to handle construction from primitive types.

You can declare a structured value type as follows:

class MyValueType
{
    Q_GADGET
    QML_VALUE_TYPE(myValueType)
    QML_STRUCTURED_VALUE
    Q_PROPERTY(double d READ d WRITE setD)
    Q_PROPERTY(string e READ e WRITE setE)
    // ...
};
					

Then you can populate a property of this type as follows:

QtObject {
    property myValueType v: ({d: 4.4, e: "a string"})
}
					

The extra parentheses are necessary to disambiguate the JavaScript object from what might be interpreted as a JavaScript code block.

You can also construct lists of values this way:

QtObject {
    property list<myValueType> v: [
        {d: 4.4, e: "a string"},
        {d: 7.1, e: "another string"}
    ]
}
					

If you make value types addressable , you can use such a type in a type assertion to explicitly construct it:

pragma ValueTypeBehavior: Addressable
QtObject {
    function process(d: real) {
        let v = {d: d, e: objectName} as myValueType;
        // v is a myValueType now
    }
}
					

该宏在 Qt 6.5 引入。

另请参阅 QML_VALUE_TYPE and QML_CONSTRUCTIBLE_VALUE .

QML_UNAVAILABLE

This macro declares the enclosing type to be unavailable in QML. It registers an internal dummy type called QQmlTypeNotAvailable as QML_FOREIGN () type, using any further QML macros you specify.

Normally, the types exported by a module 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.

范例:

#ifdef NO_GAMES_ALLOWED
struct MinehuntGame
{
    Q_GADGET
    QML_NAMED_ELEMENT(Game)
    QML_UNAVAILABLE
    QML_UNCREATABLE("Get back to work, slacker!");
};
#else
class MinehuntGame : public QObject
{
    Q_OBJECT
    QML_NAMED_ELEMENT(Game)
    // ...
};
#endif
					

This will cause any QML which attempts to use the "Game" type to produce an error message:

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

Using this technique, you only need a Q_GADGET struct to customize the error message, not a full-blown QObject . Without QML_UNCREATABLE (), QML_UNAVAILABLE still results in a more specific error message than the usual "is not a type" for completely unknown types.

注意: The class name needs to be fully qualified, even if you're already inside the namespace.

另请参阅 QML_ELEMENT , QML_NAMED_ELEMENT (), QML_UNCREATABLE (),和 QML_FOREIGN ().

QML_UNCREATABLE ( reason )

Declares that the enclosing type shall not be creatable from QML. This takes effect if the type is available in QML, by having a QML_ELEMENT or QML_NAMED_ELEMENT () macro. The reason will be emitted as error message if an attempt to create the type from QML is detected.

Some QML types are implicitly uncreatable, in particular types exposed with QML_ANONYMOUS or namespaces exposed with QML_ELEMENT or QML_NAMED_ELEMENT ().

Since Qt 6.0 you can use "" instead of a reason to use a standard message instead.

另请参阅 QML_ELEMENT , QML_NAMED_ELEMENT (),和 QML_ANONYMOUS .

QML_VALUE_TYPE ( name )

Declares the enclosing type or namespace to be available in QML, using name as the name. The type has to be a value type and the name has to be lower case.

class MyValueType
{
    Q_GADGET
    QML_VALUE_TYPE(myValueType)
    // ...
};
					

另请参阅 Choosing the Correct Integration Method Between C++ and QML and QML_NAMED_ELEMENT .