我是一位有用的助手,可以为您翻译文本。
我有一个继承自QObject的类Bar。我想在类Foo中拥有一个Bar指针的QList,并在qml中公开它。
foo.h
#ifndef FOO_H
#define FOO_H
#include <QQuickItem>
class Bar : public QObject
{
Q_OBJECT
Q_PROPERTY(int x READ x)
public:
explicit Bar(QObject *parent = nullptr)
: QObject(parent), mX(123) {}
virtual ~Bar() {}
int x() const { return mX; }
private:
int mX;
};
class Foo : public QQuickItem
{
Q_OBJECT
Q_PROPERTY(QList<QObject *> t1 READ t1)
Q_PROPERTY(QList<Bar *> t2 READ t2)
public:
explicit Foo(QQuickItem *parent = nullptr)
: QQuickItem(parent) {
mT1.append(new Bar(this));
mT1.append(new Bar(this));
mT2.append(new Bar(this));
mT2.append(new Bar(this));
}
virtual ~Foo() {}
QList<QObject *> t1() const { return mT1; }
QList<Bar *> t2() const { return mT2; }
private:
QList<QObject *> mT1;
QList<Bar *> mT2;
};
#endif // FOO_H
qmlRegisterType("Custom.Foo", 1, 0, "Foo");
主界面.qml
import QtQuick 2.6
import QtQuick.Window 2.2
import Custom.Foo 1.0
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
MouseArea {
anchors.fill: parent
onClicked: {
console.log(foo.t1)
console.log(foo.t1.x)
console.log(foo.t2)
console.log(foo.t2.x)
}
}
Foo {
id: foo
}
}
QList<QObject *>
可以正常工作,我可以访问它的成员 x
,console.log(foo.t1)
输出 qml: [Bar(0x10e4be0),Bar(0x10bd6d0)]
,但是 QList<Bar *>
不行。
当我试图访问成员 x
时,输出为 qml: undefined,console.log(foo.t2)
则输出 qml: QVariant(QList<Bar*>)
。
为什么 QList<Bar *>
在 QVariant 中被暴露?有没有办法像 QList<QObject *>
一样在 qml 中暴露它?