How to pass a function as model data?
Unsolved
QML and Qt Quick
-
wrote on 7 Jun 2016, 13:12 last edited by
How can we pass a function as data within a model ?
I am trying this way, which doesn't work :(Main.qml:
import QtQuick 2.0 import QtQuick.Window 2.2 Window { visible: true MyBtnRow { btnData: [ { tag:"Jump", action:function(){console.log (" Jump Called OK!");} }, { tag:"Run", action:(function(){console.log(" Run Called OK!");} ) }, { tag:"Hide", action:function(){console.log( " Hide Called OK!");} }, ] } }
MyBtnRow.qml
import QtQuick 2.0 Row { property var btnData // [{ tag:"Name", action: function() {... } } spacing: 3 Repeater { id: rep model: btnData Btn { id: btnId width: 60; height: 50; label.text: "Do " + modelData.tag onActivated: { try { modelData.action() } catch (err) {console.log(" catch (err:" +err.message+") in Button "+label.text);}; } } } }
Btn.qml
import QtQuick 2.0 Rectangle { id: buttonId property alias label: labelTextId signal activated; border.width: 2 Text { id: labelTextId anchors.centerIn: parent } MouseArea { id: mouseArea anchors.fill: parent onPressed: { buttonId.activated(); } } }
Thanks!
-
wrote on 8 Jun 2016, 07:11 last edited by
My dear friend, I'm afraid that QML models do not allow functions as data.
Nevertheless, a workaround is not complicated:
Main.qml:
import QtQuick 2.0 import QtQuick.Window 2.2 Window { visible: true width: mb.width * 1.6 height: mb.height * 1.6 MyBtnRow { id: mb anchors.centerIn: parent btnData: [ {tag:"Jump", action:"elsewhere definded"}, {tag:"Run", action:"elsewhere definded"}, {tag:"Hide", action:"elsewhere definded"}, ] callbackList: { "Jump": function(){console.log(" Jump Called OK!"); }, "Hide": function(){console.log(" Hide Called OK!"); }, "Run": function(){console.log(" Run Called OK!"); }, } } }
MyBtnRow.qml:
import QtQuick 2.0 Row { property var btnData property var callbackList spacing: 3 Repeater { id: rep model: btnData Btn { id: btnId width: 60; height: 50; label.text: "Do " + modelData.tag onActivated: { try { callbackList[modelData.tag]() } catch (err) {console.log(" catch (err:" +err.message+") in Button "+label.text);}; } } } }
Best regards
-
wrote on 9 Jun 2016, 14:53 last edited by
That's a brilliant and elegant solution!
Thank you bro for spending your precious time with a newbie like me! -
wrote on 10 Jun 2016, 14:51 last edited byThis post is deleted!
4/4