QQmlEngine 类提供实例化 QML 组件的环境。 更多...
| 头: |
#include <QQmlEngine>
|
| CMake: |
find_package(Qt6 REQUIRED COMPONENTS Qml)
target_link_libraries(mytarget PRIVATE Qt6::Qml)
|
| qmake: |
QT += qml
|
| 继承: | QJSEngine |
| 继承者: |
| 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 |
| QQmlContext * | qmlContext (const QObject * object ) |
| QQmlEngine * | qmlEngine (const QObject * object ) |
| QML_NAMESPACE_EXTENDED ( EXTENSION_NAMESPACE ) |
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 .
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.
设置 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 .
添加 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 导入路径
添加
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 ().
添加 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.
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 ().
Clears the engine's internal component cache.
This function causes the property metadata of most components previously loaded by the engine to be destroyed. It does so by dropping unreferenced components from the engine's component cache. It does not drop components that are still referenced since that would almost certainly lead to crashes further down the line.
If no components are referenced, 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 ().
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 ().
Returns the image provider set for
providerId
if found; otherwise returns
nullptr
.
另请参阅 QQuickImageProvider .
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 ().
Returns the currently set incubation controller, or 0 if no controller has been set.
另请参阅 setIncubationController ().
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 .
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 .
另请参阅 setNetworkAccessManagerFactory ().
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 引入。
Returns true if warning messages will be output to stderr in addition to being emitted by the warnings () 信号,否则 false。
默认值为 true。
另请参阅 setOutputWarningsToStandardError ().
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 ().
Removes the image provider for providerId .
另请参阅 addImageProvider () 和 QQuickImageProvider .
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.
返回引擎的根上下文。
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.
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 ().
设置 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 ().
Sets the engine's incubation controller . The engine can only have one active controller and it does not take ownership of it.
另请参阅 incubationController ().
设置 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 ().
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 ().
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 ().
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 ().
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 ().
Returns the list of currently active URL interceptors.
[signal]
void
QQmlEngine::
warnings
(const
QList
<
QQmlError
> &
warnings
)
此信号发射,当 warnings messages are generated by QML.
返回 QQmlContext associated with object , if any. This is equivalent to QQmlEngine::contextForObject (object).
注意:
添加
#include <QtQml>
to use this function.
另请参阅 contextForObject () 和 qmlEngine ().
返回 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 ().
Behaves the same way as QML_EXTENDED_NAMESPACE with the distinction that what is being extended is a namespace and not a type.
Declares that the enclosing namespace 使用 EXTENSION_NAMESPACE as an extension to provide further enumerations in QML. This takes effect if the extended namespace 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, in the following C++ code,
namespace NS2 { Q_NAMESPACE enum class E2 { D = 3, E, F }; Q_ENUM_NS(E2) } namespace NS1 { Q_NAMESPACE QML_ELEMENT enum class E1 { A, B, C }; Q_ENUM_NS(E1) // Extends NS1 with NS2 QML_NAMESPACE_EXTENDED(NS2) }
the namespace
NS1
is extended with
NS2
和
E2
enum becomes available within
NS1
from QML.
Item { Component.onCompleted: console.log(NS1.E1.A, NS1.E2.D) }
注意: EXTENSION_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.
注意: EXTENSION_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_EXTENDED_NAMESPACE (), QML_ELEMENT , QML_NAMED_ELEMENT (), QML_EXTENDED (), Registering Extension Objects , Q_ENUM ,和 Q_ENUM_NS .