使用QQmlContext :: setContextObject使C ++对象对QML可见

时间:2013-10-22 11:41:23

标签: c++ qt qml

编辑:问题已解决。请参阅下面的编辑

我无法使用QQmlContext :: setContextObject来使C ++对象对QML可见。我已经在link阅读了QQmlContext的文档,这表明我可以使用setContextObject使QML派生类的Q_PROPERTY对QML可见。以下代码说明了问题。

的main.cpp

#include <QObject>
#include <QQmlEngine>
#include <QGuiApplication>

class MyClass : public QObject
{
   Q_OBJECT
   Q_PROPERTY(QString myProperty READ prop NOTIFY propChanged)

public:
   MyClass(QObject * parent = 0) : QObject(parent) {}
   QString prop() { return QString("Hello from MyClass"); }

Q_SIGNALS:
   void propChanged(void);
};

int main(int argc, char *argv[])
{
   QGuiApplication app(argc, argv);

   QQmlEngine engine;
   QQmlContext *objectContext = new QQmlContext(engine.rootContext());
   MyClass myClass;
   objectContext->setContextObject(&myClass);

   QQmlComponent component(&engine, "main.qml");
   QObject *object = component.create(objectContext);

   return app.exec();
}

main.qml

import QtQuick 2.1
import QtQuick.Controls 1.0

ApplicationWindow
{
   Text
   {
      text: myProperty
   }
}

当我运行此程序时,我收到错误

file:///C:/Path/to/main.qml:8: ReferenceError: myProperty is not defined

提前感谢您的帮助。

环境。我在Windows 7上使用Qt 5.1.1,使用MSVC2010编译器


编辑。回答我自己的问题。干净的重建显示我的构建输出文件夹中明显包含一些过时的对象。

需要注意的一点是:MyClass必须位于一个单独的文件中,否则moc编译器无法发挥其魔力。

我整理的main.cpp现在看起来像这样

int main(int argc, char *argv[])
{
   QGuiApplication app(argc, argv);

   QQmlEngine engine;
   QQmlContext * context = new QQmlContext(engine.rootContext());

   QObject::connect(&engine, SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit    ()));

   MyClass myClass;
   context->setContextObject(&myClass);

   QQmlComponent component(&engine, "main.qml");
   QQuickWindow * topLevel = qobject_cast<QQuickWindow*>(component.create(context));
   topLevel->show();

   int rc = app.exec();

   delete topLevel;
   delete context;
   return rc;
}

1 个答案:

答案 0 :(得分:0)

您可以尝试在getter函数decalration中添加Q_INVOKABLE宏。如果它没有帮助,您可以考虑使用QQmlContext::setContextProperty来执行此操作。我从未见过有人使用::setContextObject进行这种集成。