passing the current instance of a cpp object to a Qml file stored in library
-
I am working on a project that provides a library of Qml files. Some of the Qml file utilize a cpp class to make some call. Now since I am just a library I dont have the current instance of that cpp class. So i need who ever is using my Qml file to pass me that object. I can get this to work with properties fine but var is a generic type so intelesense is not vary useful when developing the qml file for that library. Here is an example
Qml file from library
import QtQuick 2.8 import QtQuick.Controls 2.0 Button { // passing in cpp object here property var backend: ({}) text: backend.name }
Qml file from app
import QtQuick 2.9 import QtQuick.Controls 2.2 import Qt.labs.platform 1.0 // Load our plugin from filesystem import my.plugin.example 1.0 as MyPlugin import "plugin/MyScript.js" as MyScript ApplicationWindow { visible: true width: 640 height: 480 title: "helloworld" // 'myplugin' C++ class MyPlugin.MyQuickItem { id: pluginItem name: "pat" color: "green" width: 100 height: 50 anchors.centerIn: parent } // 'myplugin' QML file MyPlugin.MyQml { // injecting my cpp class into my qml from library backend: pluginItem anchors.top: pluginItem.bottom anchors.horizontalCenter: pluginItem.horizontalCenter width: pluginItem.width onClicked: { MyScript.onClicked(pluginItem); } } Button { width: 50 height: 50 text: pluginItem.itemName } }
this works perfectly fine but when developing intelesense would be nice so I was looking for a way to convert the property var to the specific type. then use the specific type in the qml file. here is my stab at it with no luck.
import QtQuick 2.8 import QtQuick.Controls 2.0 import my.plugin.example 1.0 as MyPlugin Button { property var backend: itemMy MyPlugin.MyQuickItem { id: itemMy } text: itemMy.name }
any help would be much appericated
-
property var backend: itemMy
At the very least you can make your
backend
variable aQtObject
:property QtObject backend: null
Since we are talking about a library, you probably expect (require) backend to have some properties, methods etc. right? Then you need to define such C++ class in your library, to act as a base class (interface) for users of your library. Then you can register your base class with QML (qmlRegisterType() etc.) and use it in QML:
property MyInterfaceClass backend: null