标题:QML中调用C++方法出现问题,求救
作者:cycloneii
日期:2013-05-14 23:13
内容:
我从QObject派生了一个类InvokableObject, 内容如下
InvokableObject.h
#ifndef INVOKEABLEOBJ_H
#define INVOKEABLEOBJ_H
#include
#include
class InvokeableObj : public QObject
{
Q_OBJECT
public:
explicit InvokeableObj(QObject *parent = 0);
Q_INVOKABLE QVariant getOptionValue(QString key) const { return key;}
signals:
public slots:
};
#endif // INVOKEABLEOBJ_HInvokableObject.cpp
#include "invokeableobj.h"
#include
InvokeableObj::InvokeableObj(QObject *parent) :
QObject(parent)
{
}main.cpp
#include
#include
#include "invokeableobj.h"
#include "qmlapplicationviewer.h"
Q_DECL_EXPORT int main(int argc, char *argv[])
{
QScopedPointer app(createApplication(argc, argv));
QmlApplicationViewer viewer;
viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
viewer.setMainQmlFile(QLatin1String("qml/testinvokable/main.qml"));
viewer.showExpanded();
viewer.rootContext()->setContextProperty("testobject", new InvokeableObj(&viewer));
return app->exec();
}main.qml
// import QtQuick 1.0 // to target S60 5th Edition or Maemo 5
import QtQuick 1.1
Rectangle {
width: 360
height: 360
Text {
id: text1
text: testobject.getOptionValue("ipaddress")
anchors.centerIn: parent
}
Mous ..
#1 [cavendish 05-14 23:56]
http://doc-snapshot.qt-project.org/4.8/qml-extending.html
QML relies heavily on Qt's meta object system and can only instantiate classes that derive from QObject. For visual element types, this will usually mean a subclass of QDeclarativeItem; for models used with the view elements, a subclass of QAbstractItemModel; and for arbitrary objects with properties, a direct subclass of QObject.
#2 [cycloneii 05-15 09:53]
引用第1楼cavendish于2013-05-14 23:56发表的:
http://doc-snapshot.qt-project.org/4.8/qml-extending.html
QML relies heavily on Qt's meta object system and can only instantiate classes that derive from QObject. For visual element types, this will usually mean a subclass of QDeclarativeItem; for models used with the view elements, a subclass of QAbstractItemModel; and for arbitrary objects with properties, a direct subclass of QObject.
并不一定要是QObject的直接子类,比如如果InvokableObject从QSettings派生,那么qml依然可以调用getOptionValue方法,但是换成QDeclarativePropertyMap就不行。其中应该还有其他的原因吧