Qt6 topics merged with General

[SOLVED] C++ object as property parameter

  • I come with a question to the integration between C++ and QML. I have read the good
    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.1

    Column {
    id: propCol
    property string objName

    Text { text: eval(propCol.objName+".number") }
    Text { text: 2 * eval(propCol.objName+".number") }
    Text { text: eval(propCol.objName+".number") * eval(propCol.objName+".number") }

    import QtQuick 2.1
    import QtQuick.Controls 1.1

    Rectangle {
    width: 320
    height: 200

    Row {
    spacing: 40

    MyPropVis { objName: "prop1" }
    MyPropVis { objName: "prop2" }

    Button {
    text: qsTr("Set 87")
    onClicked: { prop1.setnumber(87) }

    #ifndef MYPROPS_H
    #define MYPROPS_H

    #include <QObject>

    class MyProps : public QObject

    Q_PROPERTY(quint32 number READ getnumber WRITE setnumber NOTIFY numberChanged)
    explicit MyProps(quint32 init, QObject *parent = 0);

    quint32 getnumber() const { return number; }

    void numberChanged();

    public slots:
    void setnumber(quint32 localParameter);

    quint32 number;

    #endif // MYPROPS_H@

    #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);
    return app.exec();

    Thanks for any hint.

  • Moderators

    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.

  • Yeah, so simple, thanks.

    Sometimes it is hard to do the step from a strongly typed language to Javascript/QML:-)

Log in to reply