我在访问QML中的属性时遇到问题。
QList是一个属性,我可以访问它,但是当我尝试访问 QML 中classB的属性时,我收到类型错误/未定义。以下是代码:
[编辑 1] - 根据建议将 QList 更改为 QVariantList:
//ClassA.h
#include <QObject>
#include "classb.h"
Q_DECLARE_METATYPE(QList<ClassB*>)
class ClassA : public QObject
{
Q_OBJECT
Q_PROPERTY(QVariantList objList READ getClassBDetails) //[EDIT 1]
public:
explicit ClassA(QObject *parent = nullptr);
QVariantList getClassBDetails(); //[EDIT 1]
private:
QVariantList m_list; //[EDIT 1]
ClassB m_Bobj;
};
//ClassA.cpp
#include "classa.h"
ClassA::ClassA(QObject *parent) : QObject(parent)
{
m_list.append(QVariant::fromValue(&m_Bobj)); //** Appending to QvariantList
}
QVariantList ClassA ::getClassBDetails() //[EDIT 1]
{
return m_list;
}
//ClassB.h
#include <QObject>
class ClassB : public QObject
{
Q_OBJECT
Q_PROPERTY(int val READ getval WRITE setval NOTIFY valChanged)
public:
explicit ClassB(QObject *parent = nullptr);
int m_val = 10;
int getval();
void setval(int val);
signals:
void valChanged();
public slots:
};
//ClassB.cpp
#include "classb.h"
ClassB::ClassB(QObject *parent) : QObject(parent)
{
}
int ClassB::getval()
{
return m_val;
}
void ClassB::setval(int val)
{
m_val = val;
emit valChanged();
}
//main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "classa.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
ClassA aObj;
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("classAObj",&aObj);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
//main.qml
import QtQuick 2.6
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Component.onCompleted: {
console.log("value========",classAObj.objList[0].val) //** Same error
}
}
如果我尝试访问,"classAObj.objList[0].val"
我会收到TypeError: Cannot read property 'val' of undefined
错误消息。我在这里做错了什么?