我已将ObjectName设置为main中的一个类,并希望从另一个类访问此对象:
的main.cpp
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
ImageProvider *imageProvider = new ImageProvider(&engine,QQmlImageProviderBase::Image,0);
PageBuffer p;
p.setObjectName("Object");
engine.rootContext()->setContextProperty("p",&p);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
engine.addImageProvider("images", imageProvider);
return app.exec();
}
我尝试从以下位置访问PageBuffer p的课程:
QImage ImageProvider ::requestImage(const QString &id, QSize *size, const QSize &requestedSize)
{
QQuickWindow *window = qobject_cast<QQuickWindow*>(m_engine->rootObjects()[0]);
PageBuffer *p = window->findChild<PageBuffer *>("Object");
cout<<p->current_box; //error at runtime
QImage e;
e.load("Pic4.jpg");
return e;
}
但我似乎无法访问对象PageBuffer的任何成员,也许是因为指针,我怎样才能从对象p访问函数?
答案 0 :(得分:0)
您可以将pageBuffer
成员介绍给ImageProvider
:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
ImageProvider *imageProvider = new ImageProvider(&engine,QQmlImageProviderBase::Image,0);
PageBuffer p;
imageProvider->setPageBuffer(p);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
engine.addImageProvider("images", imageProvider);
return app.exec();
}
然后您不需要搜索对象孩子,您可以直接访问pageBuffer
:
QImage ImageProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize)
{
QQuickWindow *window = qobject_cast<QQuickWindow*>(m_engine->rootObjects()[0]);
PageBuffer *p = pageBuffer();
cout << p->current_box;
QImage e;
e.load("Pic4.jpg");
return e;
}