1

I have a JavaScript function in QML which creates and returns a component (Item):

function addMyComponent() {
    var component = Qt.createComponent('MyComponent.qml');
    var obj = component.createObject(container, {'x': 0, 'y': 0});
    return obj; // Not sure weather to return obj or component for my C++ to use
}

I also have some QML in main.qml which is using a custom C++ class I have made:

// ...
import com.acidic.customclass 1.0
import "AddMyComponent.js" as AddMyComponent

ApplicationWindow {
    visible: true
    width: 1280
    height: 800

    CustomClass {
        id: customClass
    }

    Button {
        onClicked: {
            customClass.receiveComponent(AddMyComponent.addMyComponent)
        }
    }
}

And my C++ class header:

Q_INVOKABLE void receiveComponent(const QObject& obj /* QObject ref doesn't work */);

and body:

void CustomClass::receiveComponent(const QObject& obj) {
    qDebug(obj.property("width")); // To see if we have received it correctly
}

How can I parse a component created with JavaScript and Qt.createComponent into my custom C++ class' function parameter?

5
  • You should use Q_INVOKABLE void receiveComponent(QObject* pObj);. Commented Feb 6, 2018 at 7:35
  • @AlexanderVX that worked! Thank you, I'd be willing to accept it as an answer if you post it Commented Feb 6, 2018 at 9:00
  • I just don't understand why this is downvoted!!! Commented Feb 6, 2018 at 13:58
  • @MohammadKanan Idk too !! :( Commented Feb 6, 2018 at 13:59
  • @Acidic Just cannot remember the proper link to docs but there few. I posted "Data Type Conversion Between QML and C++" link with the answer. At least that is some clarification. Commented Feb 6, 2018 at 14:48

1 Answer 1

3

We have QML UI objects derived from QQuickItem (for Qt Quick) which is QObject and other 'auxiliary' objects also used in QML derived from QObject base:

// QObject pointer should work with QML objects
Q_INVOKABLE void receiveComponent(QObject* pObj);

Mind that there also QString, QVariant, QVariantList, QVariantMap and other Qt primitives. For the reference.

Sign up to request clarification or add additional context in comments.

1 Comment

Also, I would recommend @Acidic tries Q_INVOKABLE void receiveComponent(QQuickItem* pQuickItem); as the initializer varlist tells me that it's likely a QQuickItem. The more specific the typing, the better the runtime performance / readability, as a general rule.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.