JS Objects

While working with JS there are some objects and methods which are more frequently used. This is a small collection of them.

  • Math.floor(v), Math.ceil(v), Math.round(v) - largest, smallest, rounded integer from float

  • Math.random() - create a random number between 0 and 1

  • Object.keys(o) - get keys from object (including QObject)

  • JSON.parse(s), JSON.stringify(o) - conversion between JS object and JSON string

  • Number.toFixed(p) - fixed precision float

  • Date - Date manipulation

You can find them also at: JavaScript referenceJS Objects - 图1 (opens new window)

Here some small and limited examples of how to use JS with QML. They should give you an idea how you can use JS inside QML

Print all keys from QML Item

  1. Item {
  2. id: root
  3. Component.onCompleted: {
  4. var keys = Object.keys(root);
  5. for(var i=0; i<keys.length; i++) {
  6. var key = keys[i];
  7. // prints all properties, signals, functions from object
  8. console.log(key + ' : ' + root[key]);
  9. }
  10. }
  11. }

Parse an object to a JSON string and back

  1. Item {
  2. property var obj: {
  3. key: 'value'
  4. }
  5. Component.onCompleted: {
  6. var data = JSON.stringify(obj);
  7. console.log(data);
  8. var obj = JSON.parse(data);
  9. console.log(obj.key); // > 'value'
  10. }
  11. }

Current Date

  1. Item {
  2. Timer {
  3. id: timeUpdater
  4. interval: 100
  5. running: true
  6. repeat: true
  7. onTriggered: {
  8. var d = new Date();
  9. console.log(d.getSeconds());
  10. }
  11. }
  12. }

Call a function by name

  1. Item {
  2. id: root
  3. function doIt() {
  4. console.log("doIt()")
  5. }
  6. Component.onCompleted: {
  7. // Call using function execution
  8. root["doIt"]();
  9. var fn = root["doIt"];
  10. // Call using JS call method (could pass in a custom this object and arguments)
  11. fn.call()
  12. }
  13. }