插件的创建非常简单,但是它可以复用,并且为不同的应用程序扩展类型。使用创建的插件是非常灵活的
解决方案。关于插件一个很好的例子见QmlBook-In-Chinese 中最后一章介绍的例子。
本文主要备忘生成插件dll,怎么引用。
1.创建插件 ,Library->Qt Quick 2 Extension Plugin
#ifndef MYITEM_H #define MYITEM_H #include <QQuickItem> class MyItem : public QQuickItem { Q_OBJECT Q_DISABLE_COPY(MyItem) public: MyItem(QQuickItem *parent = 0); ~MyItem(); Q_INVOKABLE void read(); }; #endif // MYITEM_H
#include "myitem.h" #include <QDebug> MyItem::MyItem(QQuickItem *parent): QQuickItem(parent) { // By default, QQuickItem does not draw anything. If you subclass // QQuickItem to create a visual item, you will need to uncomment the // following line and re-implement updatePaintNode() // setFlag(ItemHasContents, true); } MyItem::~MyItem() { } void MyItem::read() { qWarning() << "qml cpp plugin "; }
#pragma once #include <QQmlExtensionPlugin> class QMLCPPPluginPlugin : public QQmlExtensionPlugin { Q_OBJECT Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface") public: void registerTypes(const char *uri); };
#include "qmlcppplugin_plugin.h" #include "myitem.h" #include <qqml.h> void QMLCPPPluginPlugin::registerTypes(const char *uri) { // @uri com.mycompany.qmlcomponents qmlRegisterType<MyItem>(uri, 1, 0, "MyItem"); }
qmldir 文件
module MyPlugin
plugin QMLCPPPlugin
编译,生成release和debug QMLCPPPlugin.dll 和 QMLCPPPlugind.dll
2.应用
Application->Qt Quick Application
在应用程序新建文件夹DLL(DLL文件夹和QMLCPPPluginApp.pro同级目录),在DLL新建文件夹MyPlugin(此MyPlugin是qmldir文件中module).
把QMLCPPPlugin.dll ,QMLCPPPlugind.dll和qmldir复制到MyPlugin文件夹内。(D:Test1QMLCPPPluginAppQMLCPPPluginAppDLLMyPlugin)
指定插件DLL的路径
engine.addImportPath("D:/Test1/QMLCPPPluginApp/QMLCPPPluginApp/DLL/");
如果不指定,在Qt安装文件D:ProgramFilesQtQt5805.8mingw53_32qml目录新建文件夹MyPlugin,把QMLCPPPlugin.dll ,QMLCPPPlugind.dll和qmldir复制到MyPlugin文件夹内。
#include <QGuiApplication> #include <QQmlApplicationEngine> int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQmlApplicationEngine engine; engine.addImportPath("D:/Test1/QMLCPPPluginApp/QMLCPPPluginApp/DLL/"); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); }
import QtQuick 2.6 import QtQuick.Window 2.2 import MyPlugin 1.0 Window { visible: true 640 height: 480 title: qsTr("Hello World") MainForm { anchors.fill: parent mouseArea.onClicked: { cppPlugin.read() console.log(qsTr('Clicked on background. Text: "' + textEdit.text + '"')) } } MyItem{ id:cppPlugin } }