[SOLVED] C++ object as property parameter
-
I come with a question to the integration between C++ and QML. I have read the good
"cpp-integration":http://qt-project.org/doc/qt-5.0/qtqml/qtqml-cppintegration-definetypes.html
documentation. But I see no solution for my use case.The target is to write a module that display properties (in real a lot of properties) of a C++-Object.
At the moment I use the eval() function and it works:-), but I ask if there is a smarter solution. Here my code.@// MyPropVis.qml
import QtQuick 2.1Column {
id: propCol
property string objNameText { text: eval(propCol.objName+".number") }
Text { text: 2 * eval(propCol.objName+".number") }
Text { text: eval(propCol.objName+".number") * eval(propCol.objName+".number") }
}@@//PropMain.qml
import QtQuick 2.1
import QtQuick.Controls 1.1Rectangle {
width: 320
height: 200Row {
spacing: 40MyPropVis { objName: "prop1" }
MyPropVis { objName: "prop2" }Button {
text: qsTr("Set 87")
onClicked: { prop1.setnumber(87) }
}
}
}@@//MyProps.h
#ifndef MYPROPS_H
#define MYPROPS_H#include <QObject>
class MyProps : public QObject
{
Q_OBJECTQ_PROPERTY(quint32 number READ getnumber WRITE setnumber NOTIFY numberChanged)
public:
explicit MyProps(quint32 init, QObject *parent = 0);quint32 getnumber() const { return number; }
signals:
void numberChanged();public slots:
void setnumber(quint32 localParameter);private:
quint32 number;
};#endif // MYPROPS_H@
@//main.cpp
#include "MyProps.h"#include <QGuiApplication>
#include <QQmlContext>
#include <QQmlEngine>
#include <QQuickView>int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQuickView viewer;MyProps prop1(34);
MyProps prop2(42);viewer.rootContext()->setContextProperty("prop1", &prop1);
viewer.rootContext()->setContextProperty("prop2", &prop2);
viewer.setSource(QUrl("qrc:/qml/helloQml/PropMain.qml"));
viewer.show();
return app.exec();
}@Thanks for any hint.
-
All properties of an object (that derives from QObject) can be read in QML using dot notation.
You do not need to create your special "objName" property: all QML and QObjects have "objectName" property. By default it is empty, but you can choose to set it.
You do not need to pass your objects by string name: QML understands QObject pointers. So, instead of using
@
property string objName
@you can use:
@
property var objectPointer
@I think this might help you a bit ;) I've kept the description broad and not detailed because I do not fully understand your use case. Feel free to ask for more info if anything is unclear.