1

I've written this Basic Qml file which imports QtTest but is not a test.

import QtQuick 2.0
import QtQuick.Controls 1.4
import QtTest 1.1

ApplicationWindow {

    id: window
    width: 400
    height: 250
    visible: true

    menuBar: MenuBar {
        Menu{
            title: "alpha"
            MenuItem{ text: "print after 1 sec"; onTriggered:{printAfterDelay(1000)}}
        }
    }

    Rectangle{
        anchors.fill: parent
        color: "red"
    }

    function printAfterDelay(delay){
        wait(delay);
        console.log("print")
    }
}

Once I run it, it throws the error: ReferenceError: wait is not defined.

Does this function only work while running actual test cases or am I doing something wrong? And if it only runs with test cases, are there other alternatives (not including timer)?

PS: I'm trying to avoid timer because when the code becomes more complex and relies on multiple timers it sacrifices a lot of readability.

2 Answers2

2

You are right, wait is defined only for test cases, so it will be visible only inside

TestCase {

However I disagree that using timers will reduce readability. Take a look at this answer: How to create delay function in QML?

You define your delay function only once:

function delay(delayTime, cb) {
    timer = new Timer();
    timer.interval = delayTime;
    timer.repeat = false;
    timer.triggered.connect(cb);
    timer.start();
}

and then you can use f.e. lambda:

delay(100, function() {
    console.log("print")
})

It's only a few characters more than your code. Up to my knowledge there is no better solution in Qml.

JoshThunar
  • 452
  • 1
  • 6
  • 15
0

wait() is a method of TestCase QML type. You can't use it outside a TestCase. Yous should use events sytem or signal/slots, instead.

Using delay isn't the good answer to increase readability: if your code becomes too complex, you must refactor it and split it in smaller components.

Dimitry Ernot
  • 6,256
  • 2
  • 25
  • 37