Back to Blog home

Playing with coroutines and QML

Published on Tuesday May 29, 2018 by Jesús Fernández in QML Qt JavaScript | Comments

** aka Playing with coroutines and Qt (Part II)

From 5747a7530206ac410b6bd7c1b8490d7d389ad3a5 JavaScript Generators are supported in QML. This enables to write the Fibonacci example from the previous post using generators and QML.

Mandatory example:

import QtQuick 2.11
import QtQuick.Window 2.11
import QtQuick.Controls 2.2

Window {
property var fibonacci: function* () {
yield "0: 0"
yield "1: 1"
var f0 = 1, f1 = 0, n = 2;
while (true) {
var next = f1 + f0;
f0 = f1;
f1 = next;
yield n++ + ": " + (f0 + f1);
}
}

visible: true
width: 640
height: 480
title: qsTr("Fibonacci")

Row {
anchors.fill: parent
Button {
id: button
property var coroutine: fibonacci()
width: parent.width / 2; height: parent.height
text: coroutine.next().value
onPressed: text = coroutine.next().value
}

Button {
text: "Reset!"
width: parent.width / 2; height: parent.height
onPressed: {
button.coroutine = fibonacci()
button.text = button.coroutine.next().value
}
}
}
}

Have fun!

Subscribe to Our Blog

Stay up to date with the latest marketing, sales and service tips and news.

The blog comment system has been migrated to a new platform. If you face any issues, please let us know via feedback@qt.io.