无法调用QML函数

时间:2017-12-18 13:28:59

标签: qt qml

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

这是我的代码:

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();
}

我收到以下错误消息:

&#34; QMetaObject :: invokeMethod:没有这样的方法QQuickWindow :: bbox()&#34;

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

提前致谢。

1 个答案:

答案 0 :(得分:0)

为您的项目指定一个对象名称:

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 ) );