Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to get access to QList<QPair<int, double>> in QML



  • Hi Team,

    I am newbie to the Qt world and trying to learn Qt by doing small sample programs.
    How can I access QList of C++ elements in QML. Please find sample program

    sample.h
    class Sample : public QObject
    {
    Q_OBJECT
    Q_PROPERTY(QList<QPair<int, double>> sendList READ sendList)
    public:
    explicit Sample(QObject *parent = nullptr);
    void prepareList();
    QList<QPair<int, double>> sendList();

    private:
    QList<QPair<int, double> > m_list;
    };

    sample.cpp

    float g_f[5] = {1.5,2.5,3.5,4.5,5.5};
    int g_i[5] = {1,2,3,4,5};

    Sample::Sample(QObject *parent) : QObject(parent)
    {
    }

    void Sample::prepareList()
    {
    for(int iLoop = 0; iLoop < 5; iLoop++)
    {
    m_list.append(qMakePair(g_i[iLoop], g_f[iLoop]));
    }
    }

    QList<QPair<int, double> > Sample::sendList()
    {
    return m_list;
    }

    main.cpp
    int main(int argc, char *argv[])
    {
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    

    /* QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
    &app, [url](QObject *obj, const QUrl &objUrl) {
    if (!obj && url == objUrl)
    QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    */
    Sample obj;
    obj.prepareList();

    qmlRegisterType<Sample>("Sample", 1, 0,"Sample");
    engine.rootContext()->setContextProperty("obj", QVariant::fromValue(&obj));
    
    engine.load(url);
    return app.exec();
    

    }

    main.qml
    Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    Component.onCompleted: {
        console.log("Component Oncompleted")
        for(var i = 0; i < 5; i++)
            console.log("i = " + i + " Val = " + obj.sendList[i])
    }
    

    }


  • Moderators

    Please wrap your code in code tags:

    ```
    someCode();
    ```
    

    QML engine does not understand QPair, you need to use something else, like a QVariantMap or custom subclass of QAbstractItemModel.



  • @sierdzio
    Thanks for your quick response
    Can you please provide some pseudo code how to implement and expose QVariantMap to QML.
    Any references is appreciated


  • Moderators

    I think this article in the documentation should help: https://doc.qt.io/qt-5/qtquick-modelviewsdata-cppmodels.html



  • @sierdzio
    I think the url you provided is using a model.
    Is it possible to expose the QVariantList in the form of ( QList<QPair<int, double>>) to QML without using models.
    Can someone please provide a sample examples


Log in to reply