【发布时间】:2014-03-11 01:30:24
【问题描述】:
我正在尝试将 Qml 中的列表属性用于基础 C++ 对象。我希望能够阅读和书写它。 QQmlListProperty 的文档说只实现了 READ 函数,用于读取 和 写入对象。我收到错误消息:
无效的属性赋值:“字符串”是只读属性
当我尝试运行应用程序时。以下是相关的源文件:
main.cpp
#include <QtGui/QGuiApplication>
#include <QtQml>
#include "qtquick2applicationviewer.h"
#include "A.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
qmlRegisterType<A>("TestQmlComponents", 1, 0, "A");
QtQuick2ApplicationViewer viewer;
viewer.setMainQmlFile(QStringLiteral("qml/TestQml/main.qml"));
viewer.showExpanded();
return app.exec();
}
main.qml:
import QtQuick 2.0
import TestQmlComponents 1.0
Rectangle {
width: 360
height: 360
A {
id: a
string: [
"a", "b", "c"
]
}
Text {
text: qsTr("Hello World")
anchors.centerIn: parent
}
MouseArea {
anchors.fill: parent
onClicked: {
Qt.quit();
}
}
}
啊哈:
#ifndef A_H
#define A_H
#include <QObject>
#include <QList>
#include <QString>
#include <QtQml/QQmlListProperty>
class A : public QObject
{
Q_OBJECT
Q_PROPERTY(QQmlListProperty<QString> string READ stringList)
public:
explicit A(QObject *parent = 0);
static void addString(QQmlListProperty<QString> *list, QString *str);
void addString(QString *str);
static int stringCount(QQmlListProperty<QString> *list);
int stringCount() const;
QQmlListProperty<QString> stringList();
static QString *getString(QQmlListProperty<QString> *list, int ix);
QString *getString(int ix);
private:
QList<QString *> _string;
};
#endif // A_H
A.cpp
#include "A.h"
A::A(QObject *parent) :
QObject(parent)
{
}
void A::addString(QQmlListProperty<QString> *list, QString *str)
{
A *obj = qobject_cast<A *>(list->object);
if (obj)
obj->addString(str);
}
void A::addString(QString *str)
{
_string << str;
}
int A::stringCount(QQmlListProperty<QString> *list)
{
A *obj = qobject_cast<A *>(list->object);
if (obj)
return obj->stringCount();
return 0;
}
QString *A::getString(int ix)
{
return _string.at(ix);
}
QString *A::getString(QQmlListProperty<QString> *list, int ix)
{
A *obj = qobject_cast<A *>(list->object);
if (obj)
return obj->getString(ix);
return NULL;
}
int A::stringCount() const
{
return _string.count();
}
QQmlListProperty<QString> A::stringList()
{
return QQmlListProperty<QString>(this, NULL, addString, stringCount, getString, NULL);
}
知道我做错了什么吗?
【问题讨论】: