source: trunk/doc/src/snippets/code/doc_src_qtscript.qdoc@ 5

Last change on this file since 5 was 2, checked in by Dmitry A. Kuminov, 16 years ago

Initially imported qt-all-opensource-src-4.5.1 from Trolltech.

File size: 22.0 KB
Line 
1//! [0]
2#include <QtScript>
3//! [0]
4
5
6//! [1]
7QT += script
8//! [1]
9
10
11//! [2]
12function myInterestingScriptFunction() { ... }
13...
14myQObject.somethingChanged.connect(myInterestingScriptFunction);
15//! [2]
16
17
18//! [3]
19myQObject.somethingChanged.connect(myOtherQObject.doSomething);
20//! [3]
21
22
23//! [4]
24myQObject.somethingChanged.disconnect(myInterestingFunction);
25myQObject.somethingChanged.disconnect(myOtherQObject.doSomething);
26//! [4]
27
28
29//! [5]
30var obj = { x: 123 };
31var fun = function() { print(this.x); };
32myQObject.somethingChanged.connect(obj, fun);
33//! [5]
34
35
36//! [6]
37myQObject.somethingChanged.disconnect(obj, fun);
38//! [6]
39
40
41//! [7]
42var obj = { x: 123, fun: function() { print(this.x); } };
43myQObject.somethingChanged.connect(obj, "fun");
44//! [7]
45
46
47//! [8]
48myQObject.somethingChanged.disconnect(obj, "fun");
49//! [8]
50
51
52//! [9]
53try {
54 myQObject.somethingChanged.connect(myQObject, "slotThatDoesntExist");
55} catch (e) {
56 print(e);
57}
58//! [9]
59
60
61//! [10]
62myQObject.somethingChanged("hello");
63//! [10]
64
65
66//! [11]
67myQObject.myOverloadedSlot(10); // will call the int overload
68myQObject.myOverloadedSlot("10"); // will call the QString overload
69//! [11]
70
71
72//! [12]
73myQObject['myOverloadedSlot(int)']("10"); // call int overload; the argument is converted to an int
74myQObject['myOverloadedSlot(QString)'](10); // call QString overload; the argument is converted to a string
75//! [12]
76
77
78//! [13]
79Q_PROPERTY(bool enabled READ enabled WRITE setEnabled)
80//! [13]
81
82
83//! [14]
84myQObject.enabled = true;
85
86...
87
88myQObject.enabled = !myQObject.enabled;
89//! [14]
90
91
92//! [15]
93myDialog.okButton
94//! [15]
95
96
97//! [16]
98myDialog.okButton.objectName = "cancelButton";
99// from now on, myDialog.cancelButton references the button
100//! [16]
101
102
103//! [17]
104var okButton = myDialog.findChild("okButton");
105if (okButton != null) {
106 // do something with the OK button
107}
108
109var buttons = myDialog.findChildren(RegExp("button[0-9]+"));
110for (var i = 0; i < buttons.length; ++i) {
111 // do something with buttons[i]
112}
113//! [17]
114
115
116//! [18]
117QScriptValue myQObjectConstructor(QScriptContext *context, QScriptEngine *engine)
118{
119 // let the engine manage the new object's lifetime.
120 return engine->newQObject(new MyQObject(), QScriptEngine::ScriptOwnership);
121}
122//! [18]
123
124
125//! [19]
126class MyObject : public QObject
127{
128 Q_OBJECT
129
130public:
131 MyObject( ... );
132
133 void aNonScriptableFunction();
134
135public slots: // these functions (slots) will be available in QtScript
136 void calculate( ... );
137 void setEnabled( bool enabled );
138 bool isEnabled() const;
139
140private:
141 ....
142
143};
144//! [19]
145
146
147//! [20]
148class MyObject : public QObject
149{
150 Q_OBJECT
151
152 public:
153 Q_INVOKABLE void thisMethodIsInvokableInQtScript();
154 void thisMethodIsNotInvokableInQtScript();
155
156 ...
157};
158//! [20]
159
160
161//! [21]
162var obj = new MyObject;
163obj.setEnabled( true );
164print( "obj is enabled: " + obj.isEnabled() );
165//! [21]
166
167
168//! [22]
169var obj = new MyObject;
170obj.enabled = true;
171print( "obj is enabled: " + obj.enabled );
172//! [22]
173
174
175//! [23]
176class MyObject : public QObject
177{
178 Q_OBJECT
179 // define the enabled property
180 Q_PROPERTY( bool enabled WRITE setEnabled READ isEnabled )
181
182public:
183 MyObject( ... );
184
185 void aNonScriptableFunction();
186
187public slots: // these functions (slots) will be available in QtScript
188 void calculate( ... );
189 void setEnabled( bool enabled );
190 bool isEnabled() const;
191
192private:
193 ....
194
195};
196//! [23]
197
198
199//! [24]
200Q_PROPERTY(int nonScriptableProperty READ foo WRITE bar SCRIPTABLE false)
201//! [24]
202
203
204//! [25]
205class MyObject : public QObject
206{
207 Q_OBJECT
208 // define the enabled property
209 Q_PROPERTY( bool enabled WRITE setEnabled READ isEnabled )
210
211public:
212 MyObject( ... );
213
214 void aNonScriptableFunction();
215
216public slots: // these functions (slots) will be available in QtScript
217 void calculate( ... );
218 void setEnabled( bool enabled );
219 bool isEnabled() const;
220
221signals: // the signals
222 void enabledChanged( bool newState );
223
224private:
225 ....
226
227};
228//! [25]
229
230
231//! [26]
232function enabledChangedHandler( b )
233{
234 print( "state changed to: " + b );
235}
236
237function init()
238{
239 var obj = new MyObject();
240 // connect a script function to the signal
241 obj["enabledChanged(bool)"].connect(enabledChangedHandler);
242 obj.enabled = true;
243 print( "obj is enabled: " + obj.enabled );
244}
245//! [26]
246
247
248//! [27]
249var o = new Object();
250o.foo = 123;
251print(o.hasOwnProperty('foo')); // true
252print(o.hasOwnProperty('bar')); // false
253print(o); // calls o.toString(), which returns "[object Object]"
254//! [27]
255
256
257//! [28]
258function Person(name)
259{
260 this.name = name;
261}
262//! [28]
263
264
265//! [29]
266Person.prototype.toString = function() { return "Person(name: " + this.name + ")"; }
267//! [29]
268
269
270//! [30]
271var p1 = new Person("John Doe");
272var p2 = new Person("G.I. Jane");
273print(p1); // "Person(name: John Doe)"
274print(p2); // "Person(name: G.I. Jane)"
275//! [30]
276
277
278//! [31]
279print(p1.hasOwnProperty('name')); // 'name' is an instance variable, so this returns true
280print(p1.hasOwnProperty('toString')); // returns false; inherited from prototype
281print(p1 instanceof Person); // true
282print(p1 instanceof Object); // true
283//! [31]
284
285
286//! [32]
287function Employee(name, salary)
288{
289 Person.call(this, name); // call base constructor
290
291 this.salary = salary;
292}
293
294// set the prototype to be an instance of the base class
295Employee.prototype = new Person();
296
297// initialize prototype
298Employee.prototype.toString = function() { ... }
299//! [32]
300
301
302//! [33]
303var e = new Employee("Johnny Bravo", 5000000);
304print(e instanceof Employee); // true
305print(e instanceof Person); // true
306print(e instanceof Object); // true
307print(e instanceof Array); // false
308//! [33]
309
310
311//! [34]
312QScriptValue Person_ctor(QScriptContext *context, QScriptEngine *engine)
313{
314 QString name = context->argument(0).toString();
315 context->thisObject().setProperty("name", name);
316 return engine->undefinedValue();
317}
318//! [34]
319
320
321//! [35]
322QScriptValue Person_prototype_toString(QScriptContext *context, QScriptEngine *engine)
323{
324 QString name = context->thisObject().property("name").toString();
325 QString result = QString::fromLatin1("Person(name: %0)").arg(name);
326 return result;
327}
328//! [35]
329
330
331//! [36]
332QScriptEngine engine;
333QScriptValue ctor = engine.newFunction(Person_ctor);
334ctor.property("prototype").setProperty("toString", engine.newFunction(Person_prototype_toString));
335QScriptValue global = engine.globalObject();
336global.setProperty("Person", ctor);
337//! [36]
338
339
340//! [37]
341QScriptValue Employee_ctor(QScriptContext *context, QScriptEngine *engine)
342{
343 QScriptValue super = context->callee().property("prototype").property("constructor");
344 super.call(context->thisObject(), QScriptValueList() << context->argument(0));
345 context->thisObject().setProperty("salary", context->argument(1));
346 return engine->undefinedValue();
347}
348//! [37]
349
350
351//! [38]
352QScriptValue empCtor = engine.newFunction(Employee_ctor);
353empCtor.setProperty("prototype", global.property("Person").construct());
354global.setProperty("Employee", empCtor);
355//! [38]
356
357
358//! [39]
359Q_DECLARE_METATYPE(QPointF)
360Q_DECLARE_METATYPE(QPointF*)
361
362QScriptValue QPointF_prototype_x(QScriptContext *context, QScriptEngine *engine)
363{
364 // Since the point is not to be modified, it's OK to cast to a value here
365 QPointF point = qscriptvalue_cast<QPointF>(context->thisObject());
366 return point.x();
367}
368
369QScriptValue QPointF_prototype_setX(QScriptContext *context, QScriptEngine *engine)
370{
371 // Cast to a pointer to be able to modify the underlying C++ value
372 QPointF *point = qscriptvalue_cast<QPointF*>(context->thisObject());
373 if (!point)
374 return context->throwError(QScriptContext::TypeError, "QPointF.prototype.setX: this object is not a QPointF");
375 point->setX(context->argument(0).toNumber());
376 return engine->undefinedValue();
377}
378//! [39]
379
380
381//! [40]
382var o = new Object();
383(o.__proto__ === Object.prototype); // this evaluates to true
384//! [40]
385
386
387//! [41]
388var o = new Object();
389o.__defineGetter__("x", function() { return 123; });
390var y = o.x; // 123
391//! [41]
392
393
394//! [42]
395var o = new Object();
396o.__defineSetter__("x", function(v) { print("and the value is:", v); });
397o.x = 123; // will print "and the value is: 123"
398//! [42]
399
400
401//! [43]
402class MyObject : public QObject
403{
404 Q_OBJECT
405 ...
406};
407
408Q_DECLARE_METATYPE(MyObject*)
409
410QScriptValue myObjectToScriptValue(QScriptEngine *engine, MyObject* const &in)
411{ return engine->newQObject(in); }
412
413void myObjectFromScriptValue(const QScriptValue &object, MyObject* &out)
414{ out = qobject_cast<MyObject*>(object.toQObject()); }
415
416...
417
418qScriptRegisterMetaType(&engine, myObjectToScriptValue, myObjectFromScriptValue);
419//! [43]
420
421//! [44]
422QScriptValue QPoint_ctor(QScriptContext *context, QScriptEngine *engine)
423{
424 int x = context->argument(0).toInt32();
425 int y = context->argument(1).toInt32();
426 return engine->toScriptValue(QPoint(x, y));
427}
428
429...
430
431engine.globalObject().setProperty("QPoint", engine.newFunction(QPoint_ctor));
432//! [44]
433
434//! [45]
435QScriptValue myPrintFunction(QScriptContext *context, QScriptEngine *engine)
436{
437 QString result;
438 for (int i = 0; i < context->argumentCount(); ++i) {
439 if (i > 0)
440 result.append(" ");
441 result.append(context->argument(i).toString());
442 }
443
444 QScriptValue calleeData = context->callee().data();
445 QPlainTextEdit *edit = qobject_cast<QPlainTextEdit*>(calleeData.toQObject());
446 edit->appendPlainText(result);
447
448 return engine->undefinedValue();
449}
450//! [45]
451
452//! [46]
453int main(int argc, char **argv)
454{
455 QApplication app(argc, argv);
456
457 QScriptEngine eng;
458 QPlainTextEdit edit;
459
460 QScriptValue fun = eng.newFunction(myPrintFunction);
461 fun.setData(eng.newQObject(&edit));
462 eng.globalObject().setProperty("print", fun);
463
464 eng.evaluate("print('hello', 'world')");
465
466 edit.show();
467 return app.exec();
468}
469//! [46]
470
471
472//! [47]
473QScriptEngine eng;
474QLineEdit *edit = new QLineEdit(...);
475QScriptValue handler = eng.evaluate("function(text) { print('text was changed to', text); }");
476qScriptConnect(edit, SIGNAL(textChanged(const QString &)), QScriptValue(), handler);
477//! [47]
478
479//! [48]
480QLineEdit *edit1 = new QLineEdit(...);
481QLineEdit *edit2 = new QLineEdit(...);
482
483QScriptValue handler = eng.evaluate("function() { print('I am', this.name); }");
484QScriptValue obj1 = eng.newObject();
485obj1.setProperty("name", "the walrus");
486QScriptValue obj2 = eng.newObject();
487obj2.setProperty("name", "Sam");
488
489qScriptConnect(edit1, SIGNAL(returnPressed()), obj1, handler);
490qScriptConnect(edit2, SIGNAL(returnPressed()), obj2, handler);
491//! [48]
492
493//! [49]
494var getProperty = function(name) { return this[name]; };
495
496name = "Global Object"; // creates a global variable
497print(getProperty("name")); // "Global Object"
498
499var myObject = { name: 'My Object' };
500print(getProperty.call(myObject, "name")); // "My Object"
501
502myObject.getProperty = getProperty;
503print(myObject.getProperty("name")); // "My Object"
504
505getProperty.name = "The getProperty() function";
506getProperty.getProperty = getProperty;
507getProperty.getProperty("name"); // "The getProperty() function"
508//! [49]
509
510//! [50]
511var o = { a: 1, b: 2, sum: function() { return a + b; } };
512print(o.sum()); // reference error, or sum of global variables a and b!!
513//! [50]
514
515//! [51]
516var o = { a: 1, b: 2, sum: function() { return this.a + this.b; } };
517print(o.sum()); // 3
518//! [51]
519
520//! [52]
521QScriptValue getProperty(QScriptContext *ctx, QScriptEngine *eng)
522{
523 QString name = ctx->argument(0).toString();
524 return ctx->thisObject().property(name);
525}
526//! [52]
527
528//! [53]
529QScriptValue myCompare(QScriptContext *ctx, QScriptEngine *eng)
530{
531 double first = ctx->argument(0).toNumber();
532 double second = ctx->argument(1).toNumber();
533 int result;
534 if (first == second)
535 result = 0;
536 else if (first < second)
537 result = -1;
538 else
539 result = 1;
540 return result;
541}
542//! [53]
543
544//! [54]
545QScriptEngine eng;
546QScriptValue comparefn = eng.newFunction(myCompare);
547QScriptValue array = eng.evaluate("new Array(10, 5, 20, 15, 30)");
548array.property("sort").call(array, QScriptValueList() << comparefn);
549
550// prints "5,10,15,20,30"
551qDebug() << array.toString();
552//! [54]
553
554//! [55]
555QScriptValue rectifier(QScriptContext *ctx, QScriptEngine *eng)
556{
557 QRectF magicRect = qscriptvalue_cast<QRectF>(ctx->callee().data());
558 QRectF sourceRect = qscriptvalue_cast<QRectF>(ctx->argument(0));
559 return eng->toScriptValue(sourceRect.intersected(magicRect));
560}
561
562...
563
564QScriptValue fun = eng.newFunction(rectifier);
565QRectF magicRect = QRectF(10, 20, 30, 40);
566fun.setData(eng.toScriptValue(magicRect));
567eng.globalObject().setProperty("rectifier", fun);
568//! [55]
569
570//! [56]
571function add(a, b) {
572 return a + b;
573}
574//! [56]
575
576//! [57]
577function add() {
578 return arguments[0] + arguments[1];
579}
580//! [57]
581
582//! [58]
583QScriptValue add(QScriptContext *ctx, QScriptEngine *eng)
584{
585 double a = ctx->argument(0).toNumber();
586 double b = ctx->argument(1).toNumber();
587 return a + b;
588}
589//! [58]
590
591//! [59]
592function add() {
593 if (arguments.length != 2)
594 throw Error("add() takes exactly two arguments");
595 return arguments[0] + arguments[1];
596}
597//! [59]
598
599//! [60]
600function add() {
601 if (arguments.length != 2)
602 throw Error("add() takes exactly two arguments");
603 if (typeof arguments[0] != "number")
604 throw TypeError("add(): first argument is not a number");
605 if (typeof arguments[1] != "number")
606 throw TypeError("add(): second argument is not a number");
607 return arguments[0] + arguments[1];
608}
609//! [60]
610
611//! [61]
612function add() {
613 if (arguments.length != 2)
614 throw Error("add() takes exactly two arguments");
615 return Number(arguments[0]) + Number(arguments[1]);
616}
617//! [61]
618
619//! [62]
620QScriptValue add(QScriptContext *ctx, QScriptEngine *eng)
621{
622 if (ctx->argumentCount() != 2)
623 return ctx->throwError("add() takes exactly two arguments");
624 double a = ctx->argument(0).toNumber();
625 double b = ctx->argument(1).toNumber();
626 return a + b;
627}
628//! [62]
629
630//! [63]
631QScriptValue add(QScriptContext *ctx, QScriptEngine *eng)
632{
633 if (ctx->argumentCount() != 2)
634 return ctx->throwError("add() takes exactly two arguments");
635 if (!ctx->argument(0).isNumber())
636 return ctx->throwError(QScriptContext::TypeError, "add(): first argument is not a number");
637 if (!ctx->argument(1).isNumber())
638 return ctx->throwError(QScriptContext::TypeError, "add(): second argument is not a number");
639 double a = ctx->argument(0).toNumber();
640 double b = ctx->argument(1).toNumber();
641 return a + b;
642}
643//! [63]
644
645//! [64]
646function concat() {
647 var result = "";
648 for (var i = 0; i < arguments.length; ++i)
649 result += String(arguments[i]);
650 return result;
651}
652//! [64]
653
654//! [65]
655QScriptValue concat(QScriptContext *ctx, QScriptEngine *eng)
656{
657 QString result = "";
658 for (int i = 0; i < ctx->argumentCount(); ++i)
659 result += ctx->argument(i).toString();
660 return result;
661}
662//! [65]
663
664//! [66]
665function sort(comparefn) {
666 if (comparefn == undefined)
667 comparefn = /* the built-in comparison function */;
668 else if (typeof comparefn != "function")
669 throw TypeError("sort(): argument must be a function");
670 ...
671}
672//! [66]
673
674//! [67]
675QScriptValue sort(QScriptContext *ctx, QScriptEngine *eng)
676{
677 QScriptValue comparefn = ctx->argument(0);
678 if (comparefn.isUndefined())
679 comparefn = /* the built-in comparison function */;
680 else if (!comparefn.isFunction())
681 return ctx->throwError(QScriptContext::TypeError, "sort(): argument is not a function");
682 ...
683}
684//! [67]
685
686//! [68]
687function foo() {
688 // Let bar() take care of this.
689 print("calling bar() with " + arguments.length + "arguments");
690 var result = return bar.apply(this, arguments);
691 print("bar() returned" + result);
692 return result;
693}
694//! [68]
695
696//! [69]
697QScriptValue foo(QScriptContext *ctx, QScriptEngine *eng)
698{
699 QScriptValue bar = eng->globalObject().property("bar");
700 QScriptValue arguments = ctx->argumentsObject();
701 qDebug() << "calling bar() with" << arguments.property("length").toInt32() << "arguments";
702 QScriptValue result = bar.apply(ctx->thisObject(), arguments);
703 qDebug() << "bar() returned" << result.toString();
704 return result;
705}
706//! [69]
707
708//! [70]
709function counter() {
710 var count = 0;
711 return function() {
712 return count++;
713 }
714}
715//! [70]
716
717//! [71]
718var c1 = counter(); // create a new counter function
719var c2 = counter(); // create a new counter function
720print(c1()); // 0
721print(c1()); // 1
722print(c2()); // 0
723print(c2()); // 1
724//! [71]
725
726//! [72]
727QScriptValue counter(QScriptContext *ctx, QScriptEngine *eng)
728{
729 QScriptValue act = ctx->activationObject();
730 act.setProperty("count", 0);
731 QScriptValue result = eng->newFunction(counter_inner);
732 result.setScope(act);
733 return result;
734}
735//! [72]
736
737//! [73]
738QScriptValue counter_inner(QScriptContext *ctx, QScriptEngine *eng)
739{
740 QScriptValue outerAct = ctx->callee().scope();
741 double count = outerAct.property("count").toNumber();
742 outerAct.setProperty("count", count+1);
743 return count;
744}
745//! [73]
746
747//! [74]
748QScriptValue counter_hybrid(QScriptContext *ctx, QScriptEngine *eng)
749{
750 QScriptValue act = ctx->activationObject();
751 act.setProperty("count", 0);
752 return eng->evaluate("function() { return count++; }");
753}
754//! [74]
755
756//! [75]
757function Book(isbn) {
758 this.isbn = isbn;
759}
760
761var coolBook1 = new Book("978-0131872493");
762var coolBook2 = new Book("978-1593271473");
763//! [75]
764
765//! [76]
766QScriptValue Person_ctor(QScriptContext *ctx, QScriptEngine *eng)
767{
768 QScriptValue object;
769 if (ctx->isCalledAsConstructor()) {
770 object = ctx->thisObject();
771 } else {
772 object = eng->newObject();
773 object.setPrototype(ctx->callee().property("prototype"));
774 }
775 object.setProperty("name", ctx->argument(0));
776 return object;
777}
778//! [76]
779
780//! [77]
781QScriptContext *ctx = eng.pushContext();
782QScriptValue act = ctx->activationObject();
783act.setProperty("digit", 7);
784
785qDebug() << eng.evaluate("digit + 1").toNumber(); // 8
786
787eng.popContext();
788//! [77]
789
790//! [78]
791QScriptValue getSet(QScriptContext *ctx, QScriptEngine *eng)
792{
793 QScriptValue obj = ctx->thisObject();
794 QScriptValue data = obj.data();
795 if (!data.isValid()) {
796 data = eng->newObject();
797 obj.setData(data);
798 }
799 QScriptValue result;
800 if (ctx->argumentCount() == 1) {
801 QString str = ctx->argument(0).toString();
802 str.replace("Roberta", "Ken");
803 result = str;
804 data.setProperty("x", result);
805 } else {
806 result = data.property("x");
807 }
808 return result;
809}
810//! [78]
811
812//! [79]
813QScriptEngine eng;
814QScriptValue obj = eng.newObject();
815obj.setProperty("x", eng.newFunction(getSet),
816 QScriptValue::PropertyGetter|QScriptValue::PropertySetter);
817//! [79]
818
819//! [80]
820obj.x = "Roberta sent me";
821print(obj.x); // "Ken sent me"
822obj.x = "I sent the bill to Roberta";
823print(obj.x); // "I sent the bill to Ken"
824//! [80]
825
826//! [81]
827obj = {};
828obj.__defineGetter__("x", function() { return this._x; });
829obj.__defineSetter__("x", function(v) { print("setting x to", v); this._x = v; });
830obj.x = 123;
831//! [81]
832
833//! [82]
834myButton.text = qsTr("Hello world!");
835//! [82]
836
837//! [83]
838myButton.text = qsTranslate("MyAwesomeScript", "Hello world!");
839//! [83]
840
841//! [84]
842FriendlyConversation.prototype.greeting = function(type)
843{
844 if (FriendlyConversation['greeting_strings'] == undefined) {
845 FriendlyConversation['greeting_strings'] = [
846 QT_TR_NOOP("Hello"),
847 QT_TR_NOOP("Goodbye")
848 ];
849 }
850 return qsTr(FriendlyConversation.greeting_strings[type]);
851}
852//! [84]
853
854//! [85]
855FriendlyConversation.prototype.greeting = function(type)
856{
857 if (FriendlyConversation['greeting_strings'] == undefined) {
858 FriendlyConversation['greeting_strings'] = [
859 QT_TRANSLATE_NOOP("FriendlyConversation", "Hello"),
860 QT_TRANSLATE_NOOP("FriendlyConversation", "Goodbye")
861 ];
862 }
863 return qsTranslate("FriendlyConversation", FriendlyConversation.greeting_strings[type]);
864}
865//! [85]
866
867//! [86]
868FileCopier.prototype.showProgress = function(done, total, currentFileName)
869{
870 this.label.text = qsTr("%1 of %2 files copied.\nCopying: %3")
871 .arg(done)
872 .arg(total)
873 .arg(currentFileName));
874}
875//! [86]
876
877//! [87]
878lupdate myscript.qs -ts myscript_la.ts
879//! [87]
880
881//! [88]
882lupdate -extensions qs scripts/ -ts scripts_la.ts
883//! [88]
884
885//! [89]
886lrelease myscript_la.ts
887//! [89]
888
889//! [90]
890({ unitName: "Celsius",
891 toKelvin: function(x) { return x + 273; }
892 })
893//! [90]
894
895//! [91]
896QScriptValue object = engine.evaluate("({ unitName: 'Celsius', toKelvin: function(x) { return x + 273; } })");
897QScriptValue toKelvin = object.property("toKelvin");
898QScriptValue result = toKelvin.call(object, QScriptValueList() << 100);
899qDebug() << result.toNumber(); // 373
900//! [91]
901
902//! [92]
903QScriptValue add = engine.globalObject().property("add");
904qDebug() << add.call(QScriptValue(), QScriptValueList() << 1 << 2).toNumber(); // 3
905//! [92]
906
907//! [93]
908typedef QSharedPointer<QXmlStreamReader> XmlStreamReaderPointer;
909
910Q_DECLARE_METATYPE(XmlStreamReaderPointer)
911
912QScriptValue constructXmlStreamReader(QScriptContext *context, QScriptEngine *engine)
913{
914 if (!context->isCalledAsConstructor())
915 return context->throwError(QScriptContext::SyntaxError, "please use the 'new' operator");
916
917 QIODevice *device = qobject_cast<QIODevice*>(context->argument(0).toQObject());
918 if (!device)
919 return context->throwError(QScriptContext::TypeError, "please supply a QIODevice as first argument");
920
921 // Create the C++ object
922 QXmlStreamReader *reader = new QXmlStreamReader(device);
923
924 XmlStreamReaderPointer pointer(reader);
925
926 // store the shared pointer in the script object that we are constructing
927 return engine->newVariant(context->thisObject(), qVariantFromValue(pointer));
928}
929//! [93]
930
931//! [94]
932QScriptValue xmlStreamReader_atEnd(QScriptContext *context, QScriptEngine *)
933{
934 XmlStreamReaderPointer reader = qscriptvalue_cast<XmlStreamReaderPointer>(context->thisObject());
935 if (!reader)
936 return context->throwError(QScriptContext::TypeError, "this object is not an XmlStreamReader");
937 return reader->atEnd();
938}
939//! [94]
940
941//! [95]
942 QScriptEngine engine;
943 QScriptValue xmlStreamReaderProto = engine.newObject();
944 xmlStreamReaderProto.setProperty("atEnd", engine.newFunction(xmlStreamReader_atEnd));
945
946 QScriptValue xmlStreamReaderCtor = engine.newFunction(constructXmlStreamReader, xmlStreamReaderProto);
947 engine.globalObject().setProperty("XmlStreamReader", xmlStreamReaderCtor);
948//! [95]
Note: See TracBrowser for help on using the repository browser.