Fil*_*ski 3 c++ qt qobject qml
如果我们想在QML中使用自定义C++对象列表,我们可以使用 QQmlListProperty
在QML中注册时,我们需要指定一个QML将读取列表的函数.
文档指出,对于完整功能列表,我们需要使用此功能:
QQmlListProperty::QQmlListProperty(QObject *object, void *data, AppendFunction append,
CountFunction count, AtFunction at, ClearFunction clear)
Run Code Online (Sandbox Code Playgroud)
以下是如何在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
Run Code Online (Sandbox Code Playgroud)
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();
}
}
Run Code Online (Sandbox Code Playgroud)
在将类暴露给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
}
}
Run Code Online (Sandbox Code Playgroud)
我可以使用将项目添加到列表中或清除它的功能吗?如上所示,我可以使用函数,CountFunction
并AtFunction
使用.length
和括号.我能以某种方式使用ClearFunction
和AppendFunction
吗?
也许我不能这样做QQmlListProperty
,我应该使用QAbstractListModel
?
归档时间: |
|
查看次数: |
2920 次 |
最近记录: |