Aleksey Kontsevich
Aleksey Kontsevich

Reputation: 4991

Dynamically load QQuickWindow instead of QQuickWidget in Qt C++ unit test

In our project we have C++ unit tests for QML sources. It uses following code to load component dynamically for further processing

class MyTest {
    ...
    QScopedPointer<QQuickWidget> quickWidget;
    QQuickItem* root = nullptr;

    void setQmlSource(const QString& source)
    {
        quickWidget.reset(new QQuickWidget);
        quickWidget->rootContext()->engine()->addImportPath("qrc:/qml");
        quickWidget->setSource(QUrl::fromUserInput(source));
        root = quickWidget->rootObject();
    }
}

Worked fine for qml components like this:

my.qml:

Rectangle {
   ...
}

However when I wrapped component into Dialog

Dialog {
    ...
    Rectangle {
       ...
    }
}

it stopped to work:

Error: QQuickWidget only supports loading of root objects that derive from QQuickItem.

Which is expected as Dialog is a QQuickWindow. However trying to load QQuickItem via QQuickView like this https://doc.qt.io/qt-5/qquickview.html#details:

void MyTest::setQmlWindow(const QString& source)
{
    QQuickView *view = new QQuickView;
    view->rootContext()->engine()->addImportPath("qrc:/qml");
    view->setSource(QUrl::fromUserInput(source));
    root = view->rootObject();
}

Fails with above error as well. And loading via QQmlApplicationEngine like here https://stackoverflow.com/a/23936741/630169:

void MyTest::setQmlWindow(const QString& source)
{
    engine = new QQmlApplicationEngine;
    //engine->addImportPath("qrc:/qml");
    engine->load(QUrl::fromUserInput(source));
    QObject *myObject = engine->rootObjects().first();;
    QQuickWindow *window = qobject_cast<QQuickWindow*>(myObject);
    root = window->contentItem();
}

fails with another error:

QQmlApplicationEngine failed to load component
QWARN : MyTest::myMethodTest() module "mynamespace.mymodule" is not installed
QWARN : MyTest::myMethodTest() module "mynamespace.mymodule" is not installed
...

Why view->setSource() loads this modules correctly for Rectangle item and QQmlApplicationEngine fails to do for the same item qml source but wrapped into the Dialog?

Note: these modules are C++ and loads fine with view->setSource().

If I try to use and load via QQmlComponent like mentioned in documentation: https://doc.qt.io/qt-5/qqmlcomponent.html#details:

void MyTest::setQmlWindow(const QString& source)
{
    engine = new QQmlApplicationEngine;
    //engine->addImportPath("qrc:/qml");
    QQmlComponent *component = new QQmlComponent(engine, QUrl::fromUserInput(source));
    component->loadUrl(QUrl::fromUserInput(source));
    QQuickWindow *window = qobject_cast<QQuickWindow*>(component->create());
    root = window->contentItem();
}

if engine->addImportPath() is not called, and crash with

Loc: [Unknown file(0)]

error when engine->addImportPath() is called.

How to correctly load Dialog (QQuickWindow) and get it root QQuickItem in C++ for testing? Any ideas? Thanks!

Upvotes: -1

Views: 1292

Answers (1)

folibis
folibis

Reputation: 12854

Maybe your question is about QQuickWindow/QQuickView? How does QQuickWidget related to the issue? That just a wrapper for QQuickWindow. Anyway, I would use some QML dynamic loading wrapper instead. The idea is to load each component sequentially. The example below just illustrates the idea. If you don't need a functional testing just remove timers and Connections and play with Loader.Ready instead.

main.qml

import QtQuick 2.5
import QtQuick.Window 2.2

Window {
    id: window
    visible: true
    width: 640
    height: 480
    title: qsTr("Test window")
    property var objects: ["Item1.qml", "Item2.qml", "Item3.qml"]
    property int currentObject: 0
    property var testResults: [0, 0]
    property bool testRunning: false

    onTestRunningChanged: {
        if(window.testRunning)
            console.log("start testing");
        else
            console.log("all the objects has tested. passed: " + window.testResults[0] + ", failed: " + window.testResults[1]);
    }

    function loadObject() {
        try
        {
            loader.source = window.objects[window.currentObject];
        }
        catch(ex) {}
    }

    function checkNext(prevStatus) {
        if(!window.testRunning)
            return;

        window.testResults[prevStatus ? 0 : 1]++;
        timer.running  = false;
        console.log(window.objects[window.currentObject] + ":" + ((prevStatus) ? "passed" : "failed"))
        if(window.currentObject === window.objects.length - 1) {
            window.testRunning = false;
        } else {
            window.currentObject ++;
            loadObject();
            timer.start();
        }
    }

    Loader {
        id: loader
        anchors.centerIn: parent
        onStatusChanged: {
            if (loader.status == Loader.Error) {
                loader.source = "";
                checkNext(false);
            }
        }
    }

    Connections {
        target: loader.item
        onTestPassed: checkNext(true);
    }

    Timer {
        id: timer
        interval: 5000
        repeat: false
        onTriggered: checkNext(false);
    }

    Component.onCompleted: {
        window.testRunning = true;
        loadObject();
    }
}

Item1.qml

import QtQuick 2.0
import QtQuick.Controls 2.5

Dialog {
    id: item
    signal testPassed(bool value);
    title: "Dialog test"
    modal: true
    standardButtons: Dialog.Ok
    visible: true
    onAccepted: item.testPassed(true);
}

Item2.qml

import QtQuick 2.5
import QtQuick.Controls 2.5

Rectangle {
    id: item
    signal testPassed(bool value);

    width: 200
    height: 200
    color: "orange"

    Button {
        anchors.centerIn: parent
        text: "Test"
        onClicked: item.testPassed(true);
    }
}

Item3.qml

import QtQuick 2.5

Item {
    Itemssss {

    }
}

Upvotes: 1

Related Questions