引自https://doc.qt.io/qt-5/qtqml-modules-cppplugins.html
该QML引擎加载一个C ++插件QML。此类插件通常在QML扩展模块中提供,并且可以在导入模块的QML文档中提供供客户端使用类型。一个模块至少需要注册一种类型才能被认为是有效的。
QQmlExtensionPlugin是一个插件接口,可以创建动态加载到QML应用程序中的QML扩展。这些扩展允许自定义QML类型,并可用于QML引擎。
To write a QML extension plugin:
- Subclass QQmlExtensionPlugin
- Use the Q_PLUGIN_METADATA() macro to register the plugin with the Qt meta object system
- Override the registerTypes() method and call qmlRegisterType() to register the types to be exported by the plugin
- Write a project file for the plugin
- Create a qmldir file to describe the plugin
示例
//1.定义一个QML类型TimeModel
class TimeModel : public QObject
{
Q_OBJECT
Q_PROPERTY(int hour READ hour NOTIFY timeChanged)
Q_PROPERTY(int minute READ minute NOTIFY timeChanged)
...
};
//-------------------------注册类型qmlqtimeexampleplugin-------------------------
//继承QQmlExtensionPlugin
class QExampleQmlPlugin : public QQmlExtensionPlugin
{
Q_OBJECT
Q_PLUGIN_METADATA(IID QQmlExtensionInterface_iid)
public:
void registerTypes(const char *uri) override
{
Q_ASSERT(uri == QLatin1String("TimeExample"));
qmlRegisterType<TimeModel>(uri, 1, 0, "Time"); //将TimeModel 注册到QML中
}
};
//--------------------------pro文件---------------------------
//设置pro文件
TEMPLATE = lib
CONFIG += qt plugin
QT += qml
DESTDIR = imports/TimeExample
TARGET = qmlqtimeexampleplugin
SOURCES += qexampleqmlplugin.cpp
//--------------------qmldir定义插件-------------------------------
module TimeExample
Clock 1.0 Clock.qml
plugin qmlqtimeexampleplugin
//----------------------使用插件里的类型--------------------------------
import TimeExample 1.0 // import types from the plugin
Clock { // this class is defined in QML (imports/TimeExample/Clock.qml)
Time { // this class is defined in C++ (plugin.cpp)
id: time
}
hours: time.hour
minutes: time.minute
}
完整的源代码可在插件示例中找到。
参考
- 用C ++编写QML扩展 -包含创建QML插件的章节。
- 从C ++定义QML类型 -有关将C ++类型注册到运行时的信息。
- 如何创建Qt插件 -有关Qt插件的信息