Hi,
I’m writing a QtQuick app, and I need to use some Qt C++ functions, but when I try to access to my class method I get this error: file:///C:/QtDev/test022-build-simulator-Simulator_Qt_for_MinGW_4_4__Qt_SDK__Debug/qml/test022/MainPage.qml:20: ReferenceError: Can’t find variable: TestClass
I also tried with a small example (the source code is below), and I get the same error, please someone have an idea why I get this error?
main.cpp
#include <QtGui/QApplication>
#include <QtDeclarative>
#include "qmlapplicationviewer.h"
#include "testclass.h"
Q_DECL_EXPORT int main(int argc, char *argv[])
{
QScopedPointer<QApplication> app(createApplication(argc, argv));
QmlApplicationViewer viewer;
TestClass testClass;
QDeclarativeContext *context = viewer.rootContext();
context->setContextProperty("TestClass", &testClass);
viewer.setMainQmlFile(QLatin1String("qml/test022/main.qml"));
viewer.showExpanded();
return app->exec();
}
testclass.h
#ifndef TESTCLASS_H
#define TESTCLASS_H
#include <Qt>
#include <QObject>
#include <QDebug>
#include <QtDeclarative>
class TestClass : public QObject
{
Q_OBJECT
public:
TestClass(){}
Q_INVOKABLE QString showText(QString txt){
qDebug() << txt;
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, QUrl::fromLocalFile("qml/test022/MainPage.qml"));
if (component.status() == 1){
QObject *object = component.create();
QVariant returnedValeur;
QVariant msg = "002";
QMetaObject::invokeMethod(object, "jsFunction",Q_RETURN_ARG(QVariant, returnedValeur), Q_ARG(QVariant, msg));
qDebug() << returnedValeur.toString();
}
engine.deleteLater();
return "OK";
}
};
#endif // TESTCLASS_H
main.qml
import QtQuick 1.1
import com.nokia.symbian 1.1
import com.nokia.extras 1.1
PageStackWindow {
id: window
initialPage: MainPage {tools: toolBarLayout}
showStatusBar: true
showToolBar: true
ToolBarLayout {
id: toolBarLayout
ToolButton {
flat: true
iconSource: "toolbar-back"
onClicked: window.pageStack.depth <= 1 ? Qt.quit() : window.pageStack.pop()
}
}
}
MainPage.qml
import QtQuick 1.1
import com.nokia.symbian 1.1
import com.nokia.extras 1.1
Page {
id: mainPage
function jsFunction(jsVar){
console.log(jsVar)
return "003"
}
Text {
anchors.centerIn: parent
text: qsTr("Hello world!")
color: platformStyle.colorNormalLight
font.pixelSize: 20
}
Component.onCompleted: TestClass.showText("001")
}
↧