user4672929
user4672929

Reputation:

QML UnitTest missing C++ context property

I found this older post which faces the same problem: How to mock a QML component

Unfortunately, there's no solution. To recap the problem: I have a QML TestCase which imports a module. But this module relies on a root context property which normally would be added in the main.cpp. Since this is a TestCase, I have no influence on how the QQmlApplicationEngine starts up.

How can I add the missing context property?

Upvotes: 7

Views: 665

Answers (2)

BluRay
BluRay

Reputation: 66

If your module relies on a root context property, you should think to create a c++ Plugin for QML using QQmlEngineExtensionPlugin

Creating C++ Plugins for QML

If you take a look at the implementation you will need to reimplement the following function:

void initializeEngine(QQmlEngine *engine, const char *uri) override;

As the documentation says:

Initializes the extension from the uri using the engine. Here an application plugin might, for example, expose some data or objects to QML, as context properties on the engine's root context.

In this function you can put your required root context property

void initializeEngine(QQmlEngine *engine, const char *uri) override
{
  MyObject* object = new MyObject(engine->rootContext());
  engine->rootContext()->setContextProperty("myProperty", object);
}

After that, you just need to import your QML module in your QML file, where you TestCase is defined and you won't need to use any main functions to add this object as root context property.

Upvotes: 1

arxarian
arxarian

Reputation: 397

Edit:

In Qt 5.11, there is a new chapter in Qml UnitTesting. See chapter Executing C++ Before QML Tests.

Previous answer:

You can get the instance of QQmlEngine by passing QML item to C++ side, where you can use method qmlEngine.

So, you are able to set context property by calling

qmlEngine(passedQmlItem)->rootContext()->setContextProperty("propertyName", propertyValue);

Upvotes: 0

Related Questions