为QML创建C ++插件

8 篇文章 0 订阅

引自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:

  1. 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
  2. Write a project file for the plugin
  3. 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

}




完整的源代码可在插件示例中找到

参考

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值