From 27c565c1913ef5354ef99e69235814b18f0de11c Mon Sep 17 00:00:00 2001 From: Bart Janssens Date: Sun, 8 Jan 2017 22:51:01 +0100 Subject: [PATCH] Add a background-running simulation example Issue #32 --- example/progressbar.jl | 53 +++++++++++++++++++++++++++++++++++++ example/qml/progressbar.qml | 43 ++++++++++++++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 example/progressbar.jl create mode 100644 example/qml/progressbar.qml diff --git a/example/progressbar.jl b/example/progressbar.jl new file mode 100644 index 0000000..8c3d558 --- /dev/null +++ b/example/progressbar.jl @@ -0,0 +1,53 @@ +# This example show how to update the GUI dusing a long-running simulation + +using Base.Test +using QML + +qmlfile = joinpath(dirname(Base.source_path()), "qml", "progressbar.qml") + +type SimulationState + progress::Float64 +end + +const simulation_state = SimulationState(0.0) + +# Our simulation is just a busy wait, producing progress between 0.0 and 1.0 +function simulate() + counter = 0.0 + maxcount = 1000000000.0 + while counter < maxcount + for i in 1:Int(maxcount/10) + counter += 1.0 + end + produce(counter/maxcount) + end + produce(1.0) +end + +simulation_task = Task(simulate) + +# Run a step in the simulation, restart if already finished +function step() + global simulation_state + global simulation_task + + if simulation_state.progress >= 1.0 + println("Simulation was finished, restarting") + simulation_task = Task(simulate) + end + + @show progress = consume(simulation_task) + @qmlset qmlcontext().simulation_state.progress = progress + + return +end + +# Register the stepping function function +@qmlfunction step + +# The timer will run simulation steps as fast as it can while active, yielding to the GUI after each tick +timer = QTimer() + +# All arguments after qmlfile are context properties: +@qmlapp qmlfile simulation_state timer +exec() diff --git a/example/qml/progressbar.qml b/example/qml/progressbar.qml new file mode 100644 index 0000000..244cba1 --- /dev/null +++ b/example/qml/progressbar.qml @@ -0,0 +1,43 @@ +import QtQuick 2.0 +import QtQuick.Controls 1.0 +import QtQuick.Layouts 1.0 +import org.julialang 1.0 + +ApplicationWindow { + title: "My Application" + width: 480 + height: 200 + visible: true + + // Set up timer connection + Connections { + target: timer + onTimeout: Julia.step() + } + + ColumnLayout { + spacing: 6 + anchors.centerIn: parent + + ProgressBar { + value: simulation_state.progress + onValueChanged: { + if(value >= 1.0) { + timer.stop() + } + } + } + + Button { + Layout.alignment: Qt.AlignCenter + text: "Start simulation" + onClicked: timer.start() + } + + Button { + Layout.alignment: Qt.AlignCenter + text: "Stop simulation" + onClicked: timer.stop() + } + } +}