2

I'm sending a QList from C++ to QML using signal/slot

The data is populated from a call to an external API server and after parsing the data and adding them to a QList, I emit a signal with the list, and I handle it in qml file.

    {
        qDebug() << "Get players...";
        QJsonObject obj = doc.object();
        auto status  = obj["status"].toBool();
        auto players = obj["players"].toArray();

        QList<Player*> ps;
        foreach (const QJsonValue & v, players)
        {
            auto obj = v.toObject();
            auto player = obj["player"].toObject();

            auto p = new Player();
            p->setId(player["id"].toString().toInt());
            p->setName(player["name"].toString());
            ps.append(p);
        }
        qDebug() << "got players: " << ps.count();      //this prints 4000
        emit gotPlayers(status, ps);
    }

The signal is defined like this

signals:
    void gotPlayers(bool status, QList<Player *> players);

in QML file, this is what I have

Connections {
    target: APIConnection
    onGotPlayers: {
        console.log(players);
    }
}

When onGotPlayers is called for the first time, it always prints

qml: undefined

and on any other subsequent call after that it will print

qml: QVariant(QList<Player*>)

Any suggestions on why this is happening? I know of a bug in 5.11, but I'm using 5.9.5 with MSVC2015 32 bit. does that affect

yazwas
  • 101
  • 1
  • 9
  • You can either convert your `Player` to some sort of QJsonObject or you'll need to register your type with qml using [qmlRegisterType](http://doc.qt.io/qt-5/qqmlengine.html#qmlRegisterType). The fields will also need to be properties or have Q_INVOKABLE member functions to access the data. I recommend going the `qmlRegisterType` way, or you will spend a lot of time converting between QJsonObjects and your native C++ class. – Ross Rogers Jan 02 '19 at 18:38
  • You probably didn't register the `Player` type. Also I advice you to pass the array as `QVariantList` instead of `QList`. As I remember QML supports only simple types in lists. See [this](http://doc.qt.io/qt-5/qtqml-cppintegration-data.html) documents fo more info. – folibis Jan 02 '19 at 19:47
  • I actually did register it. `qmlRegisterType("com.Game.PlayerModel", 1, 0, "PlayerModel");` and `qmlRegisterType("com.Game.Player", 1, 0, "Player");` – yazwas Jan 02 '19 at 19:59
  • @folibis I will do try to use `QVariantList` instead of `QList` and see if will solve my problem. – yazwas Jan 02 '19 at 20:01
  • QML won't work with `QList`, it needs to be `QList`, no subclass. Or you could expose a proper QAbstractItemModel – GrecKo Jan 02 '19 at 21:23
  • @GrecKo the thing is, it works as expected after the first call, the only time it does not work is the first time. – yazwas Jan 03 '19 at 02:52
  • 1
    Shouldn't you register `Player *` instead of Player? – folibis Jan 03 '19 at 05:39

0 Answers0