未能调用QML函数

根据http://doc.qt.io/qt-5/qtqml-cppintegration-interactqmlfromcpp.html一章“调用QML方法”,我尝试从C++调用main.qml中的bbox函数。未能调用QML函数

这里是我的代码:

main.qml

import QtQuick 2.0 

import QtQuick.Window 2.0

import QtLocation 5.6

import QtPositioning 5.6

Window {

width: 512

height: 512

visible: true

Item{

anchors.fill: parent

Plugin{

id: osmplugin

name: "osm"

}

Map {

anchors.fill: parent

id: map

plugin: osmplugin;

zoomLevel: (maximumZoomLevel - minimumZoomLevel)/2

center {

// The Qt Company in Oslo

latitude: 59.9485

longitude: 10.7686

}

}

Component.onCompleted:{

console.log("zoomlevel : " + map.zoomLevel)

console.log("Visible region : " + map.visibleRegion)

}

function bbox(){

return map.visibleRegion;

}

}

}

和main.cpp中

#include <QGuiApplication> 

#include <QQmlApplicationEngine>

#include <QQuickItem>

#include <QGeoRectangle>

#include <QQmlComponent>

int main(int argc, char *argv[])

{

QGuiApplication app(argc, argv);

QQmlApplicationEngine engine;

QQmlComponent component(&engine, "qrc:/main.qml");

QObject *map = component.create();

QVariant ret;

bool ok = QMetaObject::invokeMethod(map, "bbox", Qt::DirectConnection, Q_RETURN_ARG(QVariant, ret));

if (!ok){

qWarning("Fail to call qml method");

}

QGeoRectangle rect = qvariant_cast<QGeoRectangle>(ret);

return app.exec();

}

我收到以下错误信息:

“QMetaObject :: invokeMethod中:没有这样的方法QQuickWindow :: bbox()“

似乎没有找到bbox功能。你能帮我找到问题吗?

在此先感谢。

回答:

给你的项目对象名称:

Item{ 

anchors.fill: parent

objectName: "bboxObj"

function bbox(){

return map.visibleRegion;

}

}

在C使用对象名称++让你的对象:

QObject *map = component.create(); 

QObject *bboxObj= map->findChild<QObject*>("bboxObj");

,并调用方法:

if (bboxObj) 

ok = QMetaObject::invokeMethod(bboxObj, "bbox", Qt::DirectConnection, Q_RETURN_ARG(QVariant, ret));

以上是 未能调用QML函数 的全部内容, 来源链接: utcz.com/qa/263717.html

回到顶部