我正在尝试访问包含这些Person对象的QQmlListProperty的类中的Person对象的名称。我正在努力的部分是从QML文件访问变量。
所有方法和变量与原始人和生日聚会c ++文件相同。使用指向段落下面示例的链接。
我尝试的方法:我添加了Q_Property使其可读,我尝试了多种方法在qml中调用它,包括party1.guests.guest(0).name。我删除了static和const并将其公开。另外,我在主c ++文件中添加了#include QGuiApplication,QQmlApplicationEngine和QQmlContext,并使用了默认快速应用程序项目提供的第二个引擎。通常,我认为这可能是我对某些地方的指针缺乏了解。
我的代码将Text对象实现到窗口内部的Main:
import QtQuick 2.12
import QtQuick.Window 2.12
import People 1.0
Window{
visible: true
width: 640
height: 480
BirthdayParty {
id : party1
host: Person {
name: "Bob Jones"
shoeSize: 12
}
guests: [
Person { name: "Leo Hodges" },
Person { name: "Jack Smith" },
Person { name: "Anne Brown" }
]
}
Text {
id: name
text: qsTr(party1.guest(0).name)
}
}
主要c ++文件的代码:
#include <QQmlComponent>
#include <QDebug>
#include "birthdayparty.h"
#include "person.h"
int main(int argc, char ** argv)
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc,argv);
//![register list]
qmlRegisterType<BirthdayParty>("People", 1,0, "BirthdayParty");
qmlRegisterType<Person>("People", 1,0, "Person");
//![register list]
//qml engine1
QQmlApplicationEngine engine1;
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine1, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine1.load(url);
//qml engine2
QQmlEngine engine2;
QQmlComponent component(&engine2, QUrl("qrc:example.qml"));
BirthdayParty *party = qobject_cast<BirthdayParty *>(component.create());
if (party && party->host()) {
qWarning() << party->host()->name() << "is having a birthday!";
qWarning() << "They are inviting:";
for (int ii = 0; ii < party->guestCount(); ++ii)
qWarning() << " " << party->guest(ii)->name();
} else {
qWarning() << component.errors();
}
return app.exec();
}
错误:没有匹配的函数来调用“ BirthdayParty :: guest()” 情况2:* reinterpret_cast
(_ v)= _t-> guest();休息; 候选:Person * BirthdayParty :: guest(int)const 人* guest(int)const; ^ ~~~~ 预期有1个arg并提供了0个
候选者:静态Person * BirthdayParty :: guest(QQmlListProperty ,int) 静态Person guest(QQmlListProperty *,int); ^ ~~~~ 预期有2个参数,并提供了0个 ^