Add Component to QQmlListProperty from C++?



  • Hi,

    i'm trying to add Component to QQmlListProperty from C++, but i am unable to do so. I've tried almost everything. I'm trying to solve on a Example: Writing QML Extensions with C++ (Chapter 5).

    I tried it in the following way:

    int main(int argc, char *argv[])
    {
        QGuiApplication app(argc, argv);
        QQmlApplicationEngine* engine = new QQmlApplicationEngine();
        QQmlComponent* myComponent = new QQmlComponent(engine, engine);
    
        qmlRegisterType<PieChart>("Charts", 1, 0, "PieChart");
        qmlRegisterType<PieSlice>("Charts", 1, 0, "PieSlice");
        myComponent->loadUrl(QUrl(QStringLiteral("qrc:///app.qml")));
        QObject* myComponentObj=myComponent->create();
        PieChart *chart = myComponentObj->findChild<PieChart*>("PieChart");
        PieSlice *slice = new PieSlice();
        slice->setColor(QColor(0,0,0,255));
        slice->setFromAngle(110);
        slice->setAngleSpan(50);
        slice->setVisible(true);        
        chart->addSlice(slice);
        return app.exec();
    }
    
    QQmlListProperty<PieSlice> PieChart::slices()
    {
        return QQmlListProperty<PieSlice>(this, 0, &PieChart::append_slice, 0, 0, 0);
    }
    
    void PieChart::append_slice(QQmlListProperty<PieSlice> *list, PieSlice *slice)
    {    
        PieChart *chart = qobject_cast<PieChart *>(list->object);
        if (chart) {
            slice->setParentItem(chart);
            chart->m_slices.append(slice);
        }
    
    }
    //![0]
    
    void PieChart::addSlice(PieSlice *slice){    
        QQmlListProperty<PieSlice> pieSlice=slices();
        PieChart::append_slice(&pieSlice,slice);
    }
    

    Second try:
    Directly set QList<PieSlice*> chart->m_slices.append(slice);, but this also does not working. :( Method paint(QPainter *painter) in PieSlice.cpp does not call.
    Is it possible to solve this problem?
    Thank you for help



  • once you create list you will not be able to modify the list. Note that objects cannot be individually added to or removed from the list once created; to modify the contents of a list, it must be reassigned to a new list.



  • @dheerendra
    Okay, thanks for reply. At last i used static items.


Log in to reply
 

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