-1

示例...不知道我做错了什么... http://doc.qt.digia.com/4.7/qtbinding.html

在此处输入图像描述

#include <QtGui/QApplication>
#include "mainwindow.h"
#include <QtDeclarative/QDeclarativeView>
#include <QtDeclarative/QDeclarativeEngine>
#include <QtDeclarative/QDeclarativeComponent>
#include <QtDeclarative/QDeclarativeContext>
#include <QDebug>

int main(int argc, char *argv[])
{
    QDeclarativeEngine engine;
    QDeclarativeComponent component(&engine, "MyItem.qml");
    QObject *object = component.create();

    QVariant returnedValue;
    QVariant msg = "Hello from C++";
    QMetaObject::invokeMethod(object, "myQmlFunction",
            Q_RETURN_ARG(QVariant, returnedValue),
            Q_ARG(QVariant, msg));

    qDebug() << "QML function returned:" << returnedValue.toString();
    delete object;

}

// MyItem.qml
import QtQuick 1.0

Item {
    function myQmlFunction(msg) {
        console.log("Got message:", msg)
        return "some return value"
    }
}
4

1 回答 1

0

使用 QT += 声明性。请注意,您不需要添加“core”和“gui”,即使 QtCreator 可能会自动生成它们有点无用。请注意,您还从 main.cpp 中包含了 mainwindow.h,但没有使用它,所以我也在下面删除了它。这对我来说很好:

主程序

TEMPLATE = app
SOURCES += main.cpp
QT += declarative

主文件

#include <QtGui/QApplication>
#include <QtDeclarative/QDeclarativeView>
#include <QtDeclarative/QDeclarativeEngine>
#include <QtDeclarative/QDeclarativeComponent>
#include <QtDeclarative/QDeclarativeContext>
#include <QDebug>

int main(int argc, char *argv[])
{
    QDeclarativeEngine engine;
    QDeclarativeComponent component(&engine, "MyItem.qml");
    QObject *object = component.create();

    QVariant returnedValue;
    QVariant msg = "Hello from C++";
    QMetaObject::invokeMethod(object, "myQmlFunction",
        Q_RETURN_ARG(QVariant, returnedValue),
        Q_ARG(QVariant, msg));

    qDebug() << "QML function returned:" << returnedValue.toString();
    delete object;

}

然后只是运行qmake && (n)make/jom测试。

于 2013-09-12T03:45:15.420 回答