Create component from C++



  • Hi,

    I have been trying to create qml component from C++, I created it sucessfully, but it did not appear in window.

    Thanks in advance

    main.qml

    Rectangle {
        color: "white"
    }
    

    MyRect.qml

    Rectangle {
        width: 100
        height: 100
        color: "red"
    }
    

    main.cpp

    #include <QQuickWidget>
    #include <QQmlEngine>
    
    int main(int argc, char *argv[])
    {
        QApplication app(argc, argv);
    
        QQuickWidget *quickWidget = new QQuickWidget;
        quickWidget->setResizeMode(QQuickWidget::SizeRootObjectToView);
        quickWidget->resize(1200, 700);
        quickWidget->setSource(QStringLiteral("qrc:/main.qml"));
    
        quickWidget->show();
    
        QQmlComponent component(quickWidget->engine(), QUrl("qrc:/MyRect.qml"));
        qDebug() << component.create(quickWidget->rootContext());
        return app.exec();
    }
    


  • Solved by setting object parentItem


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.