function with argument in JS file called in my QML fail
-
Hello guys,
I'm trying to add argument to my JS fonction to use it in my QML form but it's not working.
here working code:
function sum() { var res = 0; var res1 = 0; var result = 0; for(var i = 0; i < listModel.count; i++){ res += parseFloat(listModel.get(i).trip_time); } for(var i1 = 0; i1 < listView.currentRow; i1++){ res1 += parseFloat(listModel.get(i1).trip_time); } result = res-res1; return result; }
but when I try to replace "trip_time" by argument like that:
function sum(column) { var res = 0; var res1 = 0; var result = 0; for(var i = 0; i < listModel.count; i++){ res += parseFloat(listModel.get(i).column); } for(var i1 = 0; i1 < listView.currentRow; i1++){ res1 += parseFloat(listModel.get(i1).column); } result = res-res1; return result; }
and call the function in my qml with:
JS.sum(trip_time)
I receive error :
ReferenceError: trip_time is not definedI used many time this method to add argument like below:
function hourtodec(hour) { var res = hour.split(":") var hours = parseInt(res[0]); var minutes = parseInt(res[1]); var dec = hours+ minutes/60; return dec; }`` and I never got this problem before... Could you help me please? Thank you very much
-
Hi,
If I understand correctly trip_time comes from your model. Where do you get it from when calling the new version ?
-
@filipdns
If I understand correctly:In your "working" example,
hour
is just a variable passed into functionhourtodec
, and is used as such.In your "non-working" code, you start with
listModel.get(i).trip_time
.trip_time
is an attribute name. You cannot "factor this out" by trying to pass a parameter intosum()
--- you can't simply define function assum(column)
and then usecolumn
inlistModel.get(i1).column
to somehow replace the need to reference thetrip_time
attribute.Unless QML --- which I know nothing about --- magically changes the syntax/behaviour of JavaScript....
-
Hello I solved the problem with :
function sum(column) { var res = 0; var res1 = 0; var result = 0; for(var i = 0; i < listModel.count; i++){ res += parseFloat(listModel.get(i)[column]); } for(var i1 = 0; i1 < listView.currentRow; i1++){ res1 += parseFloat(listModel.get(i1)[column]); } result = res-res1; return result; }
and call the function in my qml form with:
JS.sum("trip-time")
thank you for your help!!
-
@filipdns
Yes indeed, well done! Here instead of trying to usecolumn
as a direct JS property reference now you are using[column]
as a property accessor and passing the string"trip_time"
as the name of the property. In JSobject.property
refers to the same asobject["property"]
.