QML UnitTest missing C++ context property
Asked Answered
W

2

7

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?

Whoops answered 11/10, 2015 at 17:1 Comment(0)
S
1

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.

Sematic answered 8/2, 2021 at 23:28 Comment(0)
C
0

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);
Covering answered 28/6, 2016 at 13:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.