qtunit-testinggoogletestqquickitem

How to create a dummy QQuickItem in C++ at runtime


I am using Qt 5.7 & unit testing using gtest or as its called googletests.

I have a function to test which intakes a QQuickItem. To test this, I want to create a QQuickItem on fly when my unit test in run. Is it possible?

Note that I do have access to QQmlApplicationEngine or the any qml files like main.qml. However I should be able to create a dummy.qml in the resources of my tests project ?
I also thinking that doing a #include <QQmlApplicationEngine> should give me access to QQmlApplicationEngine ?

How do I create dummy QQuickItem in C++ code with some valid width & height in my unit test, & pass it to my method at runtime?


Solution

  • The easiest way to have an isolated QQuickItem object for testing would be to use a QQuickView:

    QQuickView * view = new QQuickView;
    view->setSource(QUrl(QStringLiteral("qrc:/dummy.qml")));
    QQuickItem * dummyItem = view->rootObject();
    

    Due to popular demand:

    // dummy.qml
    import QtQuick 2.0
    
    Item {
      width: 200
      height: 200
    }