Search code examples
c++qtqmlqlistqquickitem

Qt compiler error when trying to use QQmlListProperty


I'm trying to use QQmlListProperty to expose a QList from within a QQuickItem - and following the documentation at:

A simplified example:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickItem>
#include <QList>
#include <QQmlListProperty>

class GameEngine : public QQuickItem
{
    Q_OBJECT
    Q_PROPERTY(QQmlListProperty<QObject> vurms READ vurms)

public:
    explicit GameEngine(QQuickItem *parent = 0) :
        QQuickItem(parent)
    {
    }

    QQmlListProperty<QObject> vurms() const
    {
        return QQmlListProperty<QObject>(this, &m_vurms);
    }

protected:
    QList<QObject*> m_vurms;
};

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    return app.exec();
}

#include "main.moc"

But I'm getting a compiler error on return QQmlListProperty<QObject>(this, &m_vurms);:

main.cpp:20: error: C2440: '<function-style-cast>': cannot convert from 'initializer list' to 'QQmlListProperty<QObject>'

I've also tried replacing the QList of Vurm with a QList of int - the problem seems to be in whatever Qt is doing in QQmlListProperty<T>(this, &m_vurms);

I am writing/compiling using Qt 5.8 and C++11 is set in the .pro file. I'm compiling in Qt Creator 4.2.1 on Windows 10: using MSVC 2015 64-bit for compiling.


Solution

  • I missed this earlier, but you need to pass a reference as the second argument to the constructor, not a pointer:

    QQmlListProperty<Vurm> GameEngine::vurms()
    {
        return QQmlListProperty<Vurm>(this, m_vurms);
    }
    

    I also had to remove the const qualifier to get it to compile, which makes sense, given that the constructor of QQmlListProperty expects a non-const pointer. The error probably remained when you tried removing it because you were still passing a pointer.