简体   繁体   中英

C++/QML sequence data exchange

Is it possible to expose QList<T> from C++ to QML, where T type is known by meta object system?

//C++:
class Data : public QObject {
    Q_OBJECT
    Q_PROPERTY(QList<QGeoCoordinate> path READ path WRITE setPath NOTIFY pathChanged)

An Data instance exposed as context property to QML, but at QML side path property is undefined. In docs written

In particular, QML currently supports:

 QList<int> QList<qreal> QList<bool> QList<QString> and QStringList QList<QUrl> 

Other sequence types are not supported transparently, and instead an instance of any other sequence type will be passed between QML and C++ as an opaque QVariantList.

But looks like that opaque conversion to QVariantList doesn't work. I'm using Qt 5.6 RC snapshot.

I'm not sure about what exactly is supposed to happen with the conversion to QVariantList . I don't see how you'd be able to access the contents of the list anyway, as the contained type is not a QObject . I think that the documentation could be made clearer there.

You can use QQmlListProperty instead, though. The Extending QML using Qt C++ has more information on its use. Here's directory.cpp from that example's source code:

/*
    Function to append data into list property
*/
void appendFiles(QQmlListProperty<File> *property, File *file)
{
    Q_UNUSED(property)
    Q_UNUSED(file)
    // Do nothing. can't add to a directory using this method
}

/*
    Function called to retrieve file in the list using an index
*/
File* fileAt(QQmlListProperty<File> *property, int index)
{
    return static_cast< QList<File *> *>(property->data)->at(index);
}

/*
    Returns the number of files in the list
*/
int filesSize(QQmlListProperty<File> *property)
{
    return static_cast< QList<File *> *>(property->data)->size();
}

/*
    Function called to empty the list property contents
*/
void clearFilesPtr(QQmlListProperty<File> *property)
{
    return static_cast< QList<File *> *>(property->data)->clear();
}

/*
    Returns the list of files as a QQmlListProperty.
*/
QQmlListProperty<File> Directory::files()
{
    refresh();
    return QQmlListProperty<File>(this, &m_fileList, &appendFiles, &filesSize, &fileAt, &clearFilesPtr);
}

You could also do something similar by exposing a QList of QObject -derived types , but that has its own fallbacks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM