Debian Codegraph @

src/script/doc/snippets/code/doc_src_qtscript.cpp

raw symbols SCIP
1 /****************************************************************************
2 **
3 ** Copyright (C) 2017 The Qt Company Ltd.
4 ** Contact: https://www.qt.io/licensing/
5 **
6 ** This file is part of the documentation of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:BSD$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
17 ** BSD License Usage
18 ** Alternatively, you may use this file under the terms of the BSD license
19 ** as follows:
20 **
21 ** "Redistribution and use in source and binary forms, with or without
22 ** modification, are permitted provided that the following conditions are
23 ** met:
24 ** * Redistributions of source code must retain the above copyright
25 ** notice, this list of conditions and the following disclaimer.
26 ** * Redistributions in binary form must reproduce the above copyright
27 ** notice, this list of conditions and the following disclaimer in
28 ** the documentation and/or other materials provided with the
29 ** distribution.
30 ** * Neither the name of The Qt Company Ltd nor the names of its
31 ** contributors may be used to endorse or promote products derived
32 ** from this software without specific prior written permission.
33 **
34 **
35 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46 **
47 ** $QT_END_LICENSE$
48 **
49 ****************************************************************************/
50
51 //! [0]
52 #include <QtScript>
53 //! [0]
54
55 //! [13]
56 Q_PROPERTY(bool enabled READ enabled WRITE setEnabled)
57 //! [13]
58
59 //! [18]
60 QScriptValue myQObjectConstructor(QScriptContext *context, QScriptEngine *engine)
61 {
62 // let the engine manage the new object's lifetime.
63 return engine->newQObject(new MyQObject(), QScriptEngine::ScriptOwnership);
64 }
65 //! [18]
66
67
68 //! [19]
69 class MyObject : public QObject
70 {
71 Q_OBJECT
72
73 public:
74 MyObject( ... );
75
76 void aNonScriptableFunction();
77
78 public slots: // these functions (slots) will be available in Qt Script
79 void calculate( ... );
80 void setEnabled( bool enabled );
81 bool isEnabled() const;
82
83 private:
84 ....
85
86 };
87 //! [19]
88
89
90 //! [20]
91 class MyObject : public QObject
92 {
93 Q_OBJECT
94
95 public:
96 Q_INVOKABLE void thisMethodIsInvokableInQtScript();
97 void thisMethodIsNotInvokableInQtScript();
98
99 ...
100 };
101 //! [20]
102
103
104 //! [23]
105 class MyObject : public QObject
106 {
107 Q_OBJECT
108 // define the enabled property
109 Q_PROPERTY( bool enabled WRITE setEnabled READ isEnabled )
110
111 public:
112 MyObject( ... );
113
114 void aNonScriptableFunction();
115
116 public slots: // these functions (slots) will be available in Qt Script
117 void calculate( ... );
118 void setEnabled( bool enabled );
119 bool isEnabled() const;
120
121 private:
122 ....
123
124 };
125 //! [23]
126
127
128 //! [24]
129 Q_PROPERTY(int nonScriptableProperty READ foo WRITE bar SCRIPTABLE false)
130 //! [24]
131
132
133 //! [25]
134 class MyObject : public QObject
135 {
136 Q_OBJECT
137 // define the enabled property
138 Q_PROPERTY( bool enabled WRITE setEnabled READ isEnabled )
139
140 public:
141 MyObject( ... );
142
143 void aNonScriptableFunction();
144
145 public slots: // these functions (slots) will be available in Qt Script
146 void calculate( ... );
147 void setEnabled( bool enabled );
148 bool isEnabled() const;
149
150 signals: // the signals
151 void enabledChanged( bool newState );
152
153 private:
154 ....
155
156 };
157 //! [25]
158
159
160 //! [34]
161 QScriptValue Person_ctor(QScriptContext *context, QScriptEngine *engine)
162 {
163 QString name = context->argument(0).toString();
164 context->thisObject().setProperty("name", name);
165 return engine->undefinedValue();
166 }
167 //! [34]
168
169
170 //! [35]
171 QScriptValue Person_prototype_toString(QScriptContext *context, QScriptEngine *engine)
172 {
173 QString name = context->thisObject().property("name").toString();
174 QString result = QString::fromLatin1("Person(name: %0)").arg(name);
175 return result;
176 }
177 //! [35]
178
179
180 //! [36]
181 QScriptEngine engine;
182 QScriptValue ctor = engine.newFunction(Person_ctor);
183 ctor.property("prototype").setProperty("toString", engine.newFunction(Person_prototype_toString));
184 QScriptValue global = engine.globalObject();
185 global.setProperty("Person", ctor);
186 //! [36]
187
188
189 //! [37]
190 QScriptValue Employee_ctor(QScriptContext *context, QScriptEngine *engine)
191 {
192 QScriptValue super = context->callee().property("prototype").property("constructor");
193 super.call(context->thisObject(), QScriptValueList() << context->argument(0));
194 context->thisObject().setProperty("salary", context->argument(1));
195 return engine->undefinedValue();
196 }
197 //! [37]
198
199
200 //! [38]
201 QScriptValue empCtor = engine.newFunction(Employee_ctor);
202 empCtor.setProperty("prototype", global.property("Person").construct());
203 global.setProperty("Employee", empCtor);
204 //! [38]
205
206
207 //! [39]
208 Q_DECLARE_METATYPE(QPointF)
209 Q_DECLARE_METATYPE(QPointF*)
210
211 QScriptValue QPointF_prototype_x(QScriptContext *context, QScriptEngine *engine)
212 {
213 // Since the point is not to be modified, it's OK to cast to a value here
214 QPointF point = qscriptvalue_cast<QPointF>(context->thisObject());
215 return point.x();
216 }
217
218 QScriptValue QPointF_prototype_setX(QScriptContext *context, QScriptEngine *engine)
219 {
220 // Cast to a pointer to be able to modify the underlying C++ value
221 QPointF *point = qscriptvalue_cast<QPointF*>(context->thisObject());
222 if (!point)
223 return context->throwError(QScriptContext::TypeError, "QPointF.prototype.setX: this object is not a QPointF");
224 point->setX(context->argument(0).toNumber());
225 return engine->undefinedValue();
226 }
227 //! [39]
228
229
230 //! [43]
231 class MyObject : public QObject
232 {
233 Q_OBJECT
234 ...
235 };
236
237 Q_DECLARE_METATYPE(MyObject*)
238
239 QScriptValue myObjectToScriptValue(QScriptEngine *engine, MyObject* const &in)
240 { return engine->newQObject(in); }
241
242 void myObjectFromScriptValue(const QScriptValue &object, MyObject* &out)
243 { out = qobject_cast<MyObject*>(object.toQObject()); }
244
245 ...
246
247 qScriptRegisterMetaType(&engine, myObjectToScriptValue, myObjectFromScriptValue);
248 //! [43]
249
250 //! [44]
251 QScriptValue QPoint_ctor(QScriptContext *context, QScriptEngine *engine)
252 {
253 int x = context->argument(0).toInt32();
254 int y = context->argument(1).toInt32();
255 return engine->toScriptValue(QPoint(x, y));
256 }
257
258 ...
259
260 engine.globalObject().setProperty("QPoint", engine.newFunction(QPoint_ctor));
261 //! [44]
262
263 //! [45]
264 QScriptValue myPrintFunction(QScriptContext *context, QScriptEngine *engine)
265 {
266 QString result;
267 for (int i = 0; i < context->argumentCount(); ++i) {
268 if (i > 0)
269 result.append(" ");
270 result.append(context->argument(i).toString());
271 }
272
273 QScriptValue calleeData = context->callee().data();
274 QPlainTextEdit *edit = qobject_cast<QPlainTextEdit*>(calleeData.toQObject());
275 edit->appendPlainText(result);
276
277 return engine->undefinedValue();
278 }
279 //! [45]
280
281 //! [46]
282 int main(int argc, char **argv)
283 {
284 QApplication app(argc, argv);
285
286 QScriptEngine eng;
287 QPlainTextEdit edit;
288
289 QScriptValue fun = eng.newFunction(myPrintFunction);
290 fun.setData(eng.newQObject(&edit));
291 eng.globalObject().setProperty("print", fun);
292
293 eng.evaluate("print('hello', 'world')");
294
295 edit.show();
296 return app.exec();
297 }
298 //! [46]
299
300
301 //! [47]
302 QScriptEngine eng;
303 QLineEdit *edit = new QLineEdit(...);
304 QScriptValue handler = eng.evaluate("(function(text) { print('text was changed to', text); })");
305 qScriptConnect(edit, SIGNAL(textChanged(const QString &)), QScriptValue(), handler);
306 //! [47]
307
308 //! [48]
309 QLineEdit *edit1 = new QLineEdit(...);
310 QLineEdit *edit2 = new QLineEdit(...);
311
312 QScriptValue handler = eng.evaluate("(function() { print('I am', this.name); })");
313 QScriptValue obj1 = eng.newObject();
314 obj1.setProperty("name", "the walrus");
315 QScriptValue obj2 = eng.newObject();
316 obj2.setProperty("name", "Sam");
317
318 qScriptConnect(edit1, SIGNAL(returnPressed()), obj1, handler);
319 qScriptConnect(edit2, SIGNAL(returnPressed()), obj2, handler);
320 //! [48]
321
322 //! [52]
323 QScriptValue getProperty(QScriptContext *ctx, QScriptEngine *eng)
324 {
325 QString name = ctx->argument(0).toString();
326 return ctx->thisObject().property(name);
327 }
328 //! [52]
329
330 //! [53]
331 QScriptValue myCompare(QScriptContext *ctx, QScriptEngine *eng)
332 {
333 double first = ctx->argument(0).toNumber();
334 double second = ctx->argument(1).toNumber();
335 int result;
336 if (first == second)
337 result = 0;
338 else if (first < second)
339 result = -1;
340 else
341 result = 1;
342 return result;
343 }
344 //! [53]
345
346 //! [54]
347 QScriptEngine eng;
348 QScriptValue comparefn = eng.newFunction(myCompare);
349 QScriptValue array = eng.evaluate("new Array(10, 5, 20, 15, 30)");
350 array.property("sort").call(array, QScriptValueList() << comparefn);
351
352 // prints "5,10,15,20,30"
353 qDebug() << array.toString();
354 //! [54]
355
356 //! [55]
357 QScriptValue rectifier(QScriptContext *ctx, QScriptEngine *eng)
358 {
359 QRectF magicRect = qscriptvalue_cast<QRectF>(ctx->callee().data());
360 QRectF sourceRect = qscriptvalue_cast<QRectF>(ctx->argument(0));
361 return eng->toScriptValue(sourceRect.intersected(magicRect));
362 }
363
364 ...
365
366 QScriptValue fun = eng.newFunction(rectifier);
367 QRectF magicRect = QRectF(10, 20, 30, 40);
368 fun.setData(eng.toScriptValue(magicRect));
369 eng.globalObject().setProperty("rectifier", fun);
370 //! [55]
371
372 //! [58]
373 QScriptValue add(QScriptContext *ctx, QScriptEngine *eng)
374 {
375 double a = ctx->argument(0).toNumber();
376 double b = ctx->argument(1).toNumber();
377 return a + b;
378 }
379 //! [58]
380
381 //! [62]
382 QScriptValue add(QScriptContext *ctx, QScriptEngine *eng)
383 {
384 if (ctx->argumentCount() != 2)
385 return ctx->throwError("add() takes exactly two arguments");
386 double a = ctx->argument(0).toNumber();
387 double b = ctx->argument(1).toNumber();
388 return a + b;
389 }
390 //! [62]
391
392 //! [63]
393 QScriptValue add(QScriptContext *ctx, QScriptEngine *eng)
394 {
395 if (ctx->argumentCount() != 2)
396 return ctx->throwError("add() takes exactly two arguments");
397 if (!ctx->argument(0).isNumber())
398 return ctx->throwError(QScriptContext::TypeError, "add(): first argument is not a number");
399 if (!ctx->argument(1).isNumber())
400 return ctx->throwError(QScriptContext::TypeError, "add(): second argument is not a number");
401 double a = ctx->argument(0).toNumber();
402 double b = ctx->argument(1).toNumber();
403 return a + b;
404 }
405 //! [63]
406
407 //! [65]
408 QScriptValue concat(QScriptContext *ctx, QScriptEngine *eng)
409 {
410 QString result = "";
411 for (int i = 0; i < ctx->argumentCount(); ++i)
412 result += ctx->argument(i).toString();
413 return result;
414 }
415 //! [65]
416
417 //! [67]
418 QScriptValue sort(QScriptContext *ctx, QScriptEngine *eng)
419 {
420 QScriptValue comparefn = ctx->argument(0);
421 if (comparefn.isUndefined())
422 comparefn = /* the built-in comparison function */;
423 else if (!comparefn.isFunction())
424 return ctx->throwError(QScriptContext::TypeError, "sort(): argument is not a function");
425 ...
426 }
427 //! [67]
428
429 //! [69]
430 QScriptValue foo(QScriptContext *ctx, QScriptEngine *eng)
431 {
432 QScriptValue bar = eng->globalObject().property("bar");
433 QScriptValue arguments = ctx->argumentsObject();
434 qDebug() << "calling bar() with" << arguments.property("length").toInt32() << "arguments";
435 QScriptValue result = bar.apply(ctx->thisObject(), arguments);
436 qDebug() << "bar() returned" << result.toString();
437 return result;
438 }
439 //! [69]
440
441 //! [72]
442 QScriptValue counter(QScriptContext *ctx, QScriptEngine *eng)
443 {
444 QScriptValue act = ctx->activationObject();
445 act.setProperty("count", 0);
446 QScriptValue result = eng->newFunction(counter_inner);
447 result.setScope(act);
448 return result;
449 }
450 //! [72]
451
452 //! [73]
453 QScriptValue counter_inner(QScriptContext *ctx, QScriptEngine *eng)
454 {
455 QScriptValue outerAct = ctx->callee().scope();
456 double count = outerAct.property("count").toNumber();
457 outerAct.setProperty("count", count+1);
458 return count;
459 }
460 //! [73]
461
462 //! [74]
463 QScriptValue counter_hybrid(QScriptContext *ctx, QScriptEngine *eng)
464 {
465 QScriptValue act = ctx->activationObject();
466 act.setProperty("count", 0);
467 return eng->evaluate("(function() { return count++; })");
468 }
469 //! [74]
470
471 //! [76]
472 QScriptValue Person_ctor(QScriptContext *ctx, QScriptEngine *eng)
473 {
474 QScriptValue object;
475 if (ctx->isCalledAsConstructor()) {
476 object = ctx->thisObject();
477 } else {
478 object = eng->newObject();
479 object.setPrototype(ctx->callee().property("prototype"));
480 }
481 object.setProperty("name", ctx->argument(0));
482 return object;
483 }
484 //! [76]
485
486 //! [77]
487 QScriptContext *ctx = eng.pushContext();
488 QScriptValue act = ctx->activationObject();
489 act.setProperty("digit", 7);
490
491 qDebug() << eng.evaluate("digit + 1").toNumber(); // 8
492
493 eng.popContext();
494 //! [77]
495
496 //! [78]
497 QScriptValue getSet(QScriptContext *ctx, QScriptEngine *eng)
498 {
499 QScriptValue obj = ctx->thisObject();
500 QScriptValue data = obj.data();
501 if (!data.isValid()) {
502 data = eng->newObject();
503 obj.setData(data);
504 }
505 QScriptValue result;
506 if (ctx->argumentCount() == 1) {
507 QString str = ctx->argument(0).toString();
508 str.replace("Roberta", "Ken");
509 result = str;
510 data.setProperty("x", result);
511 } else {
512 result = data.property("x");
513 }
514 return result;
515 }
516 //! [78]
517
518 //! [79]
519 QScriptEngine eng;
520 QScriptValue obj = eng.newObject();
521 obj.setProperty("x", eng.newFunction(getSet),
522 QScriptValue::PropertyGetter|QScriptValue::PropertySetter);
523 //! [79]
524
525 //! [91]
526 QScriptValue object = engine.evaluate("({ unitName: 'Celsius', toKelvin: function(x) { return x + 273; } })");
527 QScriptValue toKelvin = object.property("toKelvin");
528 QScriptValue result = toKelvin.call(object, QScriptValueList() << 100);
529 qDebug() << result.toNumber(); // 373
530 //! [91]
531
532 //! [92]
533 QScriptValue add = engine.globalObject().property("add");
534 qDebug() << add.call(QScriptValue(), QScriptValueList() << 1 << 2).toNumber(); // 3
535 //! [92]
536
537 //! [93]
538 typedef QSharedPointer<QXmlStreamReader> XmlStreamReaderPointer;
539
540 Q_DECLARE_METATYPE(XmlStreamReaderPointer)
541
542 QScriptValue constructXmlStreamReader(QScriptContext *context, QScriptEngine *engine)
543 {
544 if (!context->isCalledAsConstructor())
545 return context->throwError(QScriptContext::SyntaxError, "please use the 'new' operator");
546
547 QIODevice *device = qobject_cast<QIODevice*>(context->argument(0).toQObject());
548 if (!device)
549 return context->throwError(QScriptContext::TypeError, "please supply a QIODevice as first argument");
550
551 // Create the C++ object
552 QXmlStreamReader *reader = new QXmlStreamReader(device);
553
554 XmlStreamReaderPointer pointer(reader);
555
556 // store the shared pointer in the script object that we are constructing
557 return engine->newVariant(context->thisObject(), QVariant::fromValue(pointer));
558 }
559 //! [93]
560
561 //! [94]
562 QScriptValue xmlStreamReader_atEnd(QScriptContext *context, QScriptEngine *)
563 {
564 XmlStreamReaderPointer reader = qscriptvalue_cast<XmlStreamReaderPointer>(context->thisObject());
565 if (!reader)
566 return context->throwError(QScriptContext::TypeError, "this object is not an XmlStreamReader");
567 return reader->atEnd();
568 }
569 //! [94]
570
571 //! [95]
572 QScriptEngine engine;
573 QScriptValue xmlStreamReaderProto = engine.newObject();
574 xmlStreamReaderProto.setProperty("atEnd", engine.newFunction(xmlStreamReader_atEnd));
575
576 QScriptValue xmlStreamReaderCtor = engine.newFunction(constructXmlStreamReader, xmlStreamReaderProto);
577 engine.globalObject().setProperty("XmlStreamReader", xmlStreamReaderCtor);
578 //! [95]