
在QML中注册时,我们需要指定一个QML将读取列表的函数.
文档指出,对于完整功能列表,我们需要使用此功能:
QQmlListProperty::QQmlListProperty(QObject *object, void *data, AppendFunction append,
CountFunction count, AtFunction at, ClearFunction clear)
以下是如何在C中编写它的示例:
classwithlist.h
#ifndef CLASSWITHLIST_H
#define CLASSWITHLIST_H
#include <QObject>
#include <QQmlListProperty>
#include "element.h"
class Element;
class ClassWithList : public QObject
{
Q_OBJECT
Q_PROPERTY(QQmlListProperty<Element> elements READ getElements NOTIFY elementsChanged)
public:
explicit ClassWithList(QObject *parent = 0);
QQmlListProperty<Element> getElements();
void appendElements(QQmlListProperty<Element> *list, Element *e);
static int elementsCount(QQmlListProperty<Element> *list);
static Element* elementsAt(QQmlListProperty<Element> *list, int i);
static void elementsClear(QQmlListProperty<Element> *list);
signals:
void elementsChanged(QQmlListProperty<Element>);
private:
QList<Element *> m_elements;
};
#endif // CLASSWITHLIST_H
classwithlist.cpp
#include "classwithlist.h"
ClassWithList::ClassWithList(QObject *parent) : QObject(parent)
{
}
QQmlListProperty<Element> ClassWithList::getElements()
{
return QQmlListProperty<Element>(this, m_elements, &appendElements,&elementsCount,&elementsAt,&elementsClear);
}
void ClassWithList::appendElements(QQmlListProperty<Element> *list, Element *e)
{
ClassWithList *cwl = qobject_cast<ClassWithList*>(list->object);
if (cwl && e) {
cwl->m_elements.append(e);
}
}
int ClassWithList::elementsCount(QQmlListProperty<Element> *list)
{
ClassWithList *cwl = qobject_cast<ClassWithList*>(list->object);
if (cwl)
return cwl->m_elements.count();
return 0;
}
Element *ClassWithList::elementsAt(QQmlListProperty<Element> *list, int i)
{
ClassWithList *cwl = qobject_cast<ClassWithList*>(list->object);
if (cwl)
return cwl->m_elements.at(i);
return 0;
}
void ClassWithList::elementsClear(QQmlListProperty<Element> *list)
{
ClassWithList *cwl = qobject_cast<ClassWithList*>(list->object);
if (cwl) {
cwl->m_elements.clear();
}
}
在将类暴露给QML后,我在QML中有以下代码
ClassWithList {
Component.onCompleted: {
console.log(elements.length) // works
console.log(elements[0]) // works
// elements.push() // does not work
// elements.append() // does not work
// elements.clear() // does not work
// elements.at() // does not work
}
}
我可以使用将项目添加到列表中或清除它的功能吗?如上所示,我可以使用函数CountFunction和AtFunction,使用.length和括号.我可以以某种方式使用ClearFunction和AppendFunction吗?
也许我不能用QQmlListProperty做这个,我应该使用QAbstractListModel?
Values can be dynamically added to the list by using the push method, as if it were a JavaScript Array
原答案如下
您不能直接在QML中附加元素或清除QQmlListProperty.要在QML中编辑QQmlListProperty,请为其分配新列表.
根据QML清单documentation:
Any
QQmlListPropertyvalue passed into QML from C++ is automatically converted into alistvalue, and vice-versa.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.
转载注明原文:c – 如何在QML中编辑QQmlListProperty - 乐贴网