使用上下文属性将C ++对象嵌入到QML中

根据Qt5文档: 暴露方法包括qt槽,所有从QObjectinheritance的C ++类的公共槽都可以从QML访问这里我做了什么:

C ++

class MyClass : public QObject { Q_OBJECT public slots: void doStuffFromQmlSlot() { qDebug() << Q_FUNC_INFO; } public: MyClass() { qDebug() << Q_FUNC_INFO; } }; 

我的main.cpp包含:

 MyClass myClass; QQmlEngine engine; engine.rootContext()->setContextProperty( "myclass", &myClass ); QQmlComponent component( &engine, QUrl::fromLocalFile("qml/qtquick-01/main.qml") ); component.create(); 

QML

 import QtQuick 2.0 Rectangle { width: 360 height: 360 Text { text: qsTr("Hello World") anchors.centerIn: parent } MouseArea { anchors.fill: parent onClicked: { myclass.doStuffFromQmlSlot(); Qt.quit(); } } } 

实际上,QtCreator似乎将暴露的myclass对象识别为QML,因为它允许自动完成类名(myclass)和公共槽doStuffFromQmlSlot()。 当我运行应用程序时,我很遗憾地收到以下错误:

ReferenceError:未定义myclass

关于我做错了什么的任何线索?

我重用你的qml文件在QtCreator中启动一个新项目。

请在下面找到我用来编译和成功使用该应用程序的文件:

项目文件: test.pro

 # The .cpp file which was generated for your project. Feel free to hack it. SOURCES += main.cpp # Please do not modify the following two lines. Required for deployment. include(qtquick2applicationviewer/qtquick2applicationviewer.pri) qtcAddDeployment() HEADERS += myclass.h 

myclass.h:

 #include  #include  class MyClass : public QObject { Q_OBJECT public slots: void doStuffFromQmlSlot() { qDebug() << Q_FUNC_INFO; } public: MyClass() { qDebug() << Q_FUNC_INFO; } }; 

main.cpp中:

 #include  #include "qtquick2applicationviewer.h" #include  #include "myclass.h" int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); MyClass myClass; QtQuick2ApplicationViewer viewer; viewer.rootContext()->setContextProperty("myclass", &myClass); viewer.setMainQmlFile(QStringLiteral("qml/main.qml")); viewer.showExpanded(); return app.exec(); } 

qml / main.qml完全是你问题中提供的代码片段

如果你使用QtCreator启动项目,你也可以使用qtquick2applicationviewer /文件夹。 然后qmake && make && ./test将启动该应用程序。 如果单击文本元素,您将获得:

 MyClass::MyClass() void MyClass::doStuffFromQmlSlot()