Skip to content

Instantly share code, notes, and snippets.

@martinky
Last active March 26, 2020 07:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinky/f4032f9409adf1fba6f49de8a23cfe12 to your computer and use it in GitHub Desktop.
Save martinky/f4032f9409adf1fba6f49de8a23cfe12 to your computer and use it in GitHub Desktop.
Minimal example simulating a JS closure capture bug of the QML engine that is only observed while the QML debugger is attached. With the QML debugger attached following error occurs: main.qml:30: ReferenceError: text is not defined. Without QML debugger attached, the code works properly.
#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load("qrc:/main.qml");
return app.exec();
}
import QtQuick 2.6
import QtQuick.Window 2.6
import QtQuick.Controls 2.6
Window {
visible: true
width: 640
height: 480
Item {
id: logic
signal doSomething(var text)
}
Item {
id: handler
Connections {
target: logic
onDoSomething: { // signal doSomething(var text)
handler.callCallback(function(){
// The signal parameter 'text' is not captured in this closure
// and the QML engine reports: ReferenceError: text is not defined.
// But only in DEBUG mode AND only when QML debugger is attached.
// Works OK in RELEASE.
// Works OK in DEBUG without QML debugger attached.
// Whether native C++ debugger is attached has no effect.
console.log("Arg value captured in closure:", text)
console.log("You will not see this line logged when QML debugger is attached")
})
}
}
Connections {
target: logic
onDoSomething: { // signal doSomething(var text)
var v_text = text
handler.callCallback(function(){
// Workaround: evaluate the 'text' parameter outside the closure
// and capture the local variable 'v_text' instead.
console.log("Arg value captured in closure with workaround:", v_text)
})
}
}
function callCallback(callback) {
callback()
}
}
Button {
anchors.centerIn: parent
text: "Click me"
onClicked: logic.doSomething("asdf jkl")
}
}
<RCC>
<qresource prefix="/">
<file>main.qml</file>
</qresource>
</RCC>
QT += quick
CONFIG += c++11
DEFINES += QT_DEPRECATED_WARNINGS
SOURCES += main.cpp
RESOURCES += qml.qrc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment