source: trunk/doc/src/qtscript.qdoc@ 109

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

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

File size: 87.2 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4** Contact: Qt Software Information ([email protected])
5**
6** This file is part of the documentation of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial Usage
10** Licensees holding valid Qt Commercial licenses may use this file in
11** accordance with the Qt Commercial License Agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and Nokia.
14**
15** GNU Lesser General Public License Usage
16** Alternatively, this file may be used under the terms of the GNU Lesser
17** General Public License version 2.1 as published by the Free Software
18** Foundation and appearing in the file LICENSE.LGPL included in the
19** packaging of this file. Please review the following information to
20** ensure the GNU Lesser General Public License version 2.1 requirements
21** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
22**
23** In addition, as a special exception, Nokia gives you certain
24** additional rights. These rights are described in the Nokia Qt LGPL
25** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
26** package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you are unsure which license is appropriate for your use, please
37** contact the sales department at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42/*!
43 \module QtScript
44 \title QtScript Module
45 \since 4.3
46 \contentspage Qt's Modules
47 \previouspage QtOpenGL
48 \nextpage QtScriptTools
49 \ingroup modules
50 \ingroup scripting
51
52 \brief The QtScript module provides classes for making Qt applications scriptable.
53
54 \tableofcontents
55
56 \section1 Configuring the Build Process
57
58 Applications that use Qt's Script classes need to
59 be configured to be built against the QtScript module.
60 To include the definitions of the module's classes, use the
61 following directive:
62
63 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 0
64
65 To link against the module, add this line to your \l qmake \c .pro file:
66
67 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 1
68
69 The QtScript module is part of the \l{Qt Full Framework Edition} and the
70 \l{Open Source Versions of Qt}.
71
72 The QtScript module only provides core scripting facilities; the
73 QtScriptTools module provides additional Qt Script-related
74 components that application developers may find useful.
75
76 \section1 Language Overview
77
78 Qt Script is based on the ECMAScript scripting language, as defined
79 in standard \l{ECMA-262}. Microsoft's JScript, and Netscape's
80 JavaScript are also based on the ECMAScript standard. For an
81 overview of ECMAScript, see the
82 \l{ECMAScript Reference}{ECMAScript reference}.
83 If you are not familiar with the ECMAScript language, there are
84 several existing tutorials and books that cover this subject, such
85 as \l{JavaScript: The Definitive Guide}.
86
87 Existing users of \l{Qt Script for Applications (QSA)} may find the
88 \l{Moving from QSA to Qt Script} document useful when porting
89 QSA scripts to Qt Script.
90
91 \section1 Basic Usage
92
93 To evaluate script code, you create a QScriptEngine and call its
94 evaluate() function, passing the script code (text) to evaluate
95 as argument.
96
97 \snippet doc/src/snippets/qtscript/evaluation/main.cpp 0
98
99 The return value will be the result of the evaluation (represented
100 as a QScriptValue object); this can be converted to standard C++
101 and Qt types.
102
103 Custom properties can be made available to scripts by registering
104 them with the script engine. This is most easily done by setting
105 properties of the script engine's \e{Global Object}:
106
107 \snippet doc/src/snippets/qtscript/registeringvalues/main.cpp 0
108
109 This places the properties in the script environment, thus making them
110 available to script code.
111
112 \section1 Making a QObject Available to the Script Engine
113
114 Any QObject-based instance can be made available for use with scripts.
115
116 When a QObject is passed to the QScriptEngine::newQObject() function,
117 a Qt Script wrapper object is created that can be used to make the
118 QObject's signals, slots, properties, and child objects available
119 to scripts.
120
121 Here's an example of making an instance of a QObject subclass
122 available to script code under the name \c{"myObject"}:
123
124 \snippet doc/src/snippets/qtscript/registeringobjects/main.cpp 0
125
126 This will create a global variable called \c{myObject} in the
127 script environment. The variable serves as a proxy to the
128 underlying C++ object. Note that the name of the script variable
129 can be anything; i.e., it is not dependent upon QObject::objectName().
130
131 The \l{QScriptEngine::}{newQObject()} function accepts two additional
132 optional arguments: one is the ownership mode, and the other is a
133 collection of options that allow you to control certain aspects of how
134 the QScriptValue that wraps the QObject should behave. We will come
135 back to the usage of these arguments later.
136
137 \section2 Using Signals and Slots
138
139 Qt Script adapts Qt's central \l{Signals and Slots} feature for
140 scripting. There are three principal ways to use signals and slots
141 with Qt Script:
142
143 \list
144 \i \bold{Hybrid C++/script}: C++ application code connects a
145 signal to a script function. The script function can, for example, be
146 a function that the user has typed in, or one that you have read from a
147 file. This approach is useful if you have a QObject but don't want
148 to expose the object itself to the scripting environment; you just
149 want a script to be able to define how a signal should be reacted
150 to, and leave it up to the C++ side of your application to establish
151 the connection.
152
153 \i \bold{Hybrid script/C++}: A script can connect signals and slots
154 to establish connections between pre-defined objects that the
155 application exposes to the scripting environment. In this scenario,
156 the slots themselves are still written in C++, but the definition of
157 the connections is fully dynamic (script-defined).
158
159 \i \bold{Purely script-defined}: A script can both define signal
160 handler functions (effectively "slots written in Qt Script"),
161 \e{and} set up the connections that utilize those handlers. For
162 example, a script can define a function that will handle the
163 QLineEdit::returnPressed() signal, and then connect that signal to the
164 script function.
165 \endlist
166
167 Use the qScriptConnect() function to connect a C++ signal to a
168 script function. In the following example a script signal handler is
169 defined that will handle the QLineEdit::textChanged() signal:
170
171 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 47
172
173 The first two arguments to qScriptConnect() are the same
174 as you would pass to QObject::connect() to establish a normal C++
175 connection. The third argument is the script object that will act
176 as the \c this object when the signal handler is invoked; in the above
177 example we pass an invalid script value, so the \c this object will
178 be the Global Object. The fourth argument is the script function
179 ("slot") itself. The following example shows how the \c this argument
180 can be put to use:
181
182 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 48
183
184 We create two QLineEdit objects and define a single signal handler
185 function. The connections use the same handler function, but the
186 function will be invoked with a different \c this object depending on
187 which object's signal was triggered, so the output of the print()
188 statement will be different for each.
189
190 In script code, Qt Script uses a different syntax for connecting to
191 and disconnecting from signals than the familiar C++ syntax; i.e.,
192 QObject::connect().
193 To connect to a signal, you reference the relevant signal as a property
194 of the sender object, and invoke its \c{connect()} function. There
195 are three overloads of \c{connect()}, each with a corresponding
196 \c{disconnect()} overload. The following subsections describe these
197 three forms.
198
199 \section3 Signal to Function Connections
200
201 \c{connect(function)}
202
203 In this form of connection, the argument to \c{connect()} is the
204 function to connect to the signal.
205
206 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 2
207
208 The argument can be a Qt Script function, as in the above
209 example, or it can be a QObject slot, as in
210 the following example:
211
212 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 3
213
214 When the argument is a QObject slot, the argument types of the
215 signal and slot do not necessarily have to be compatible;
216 QtScript will, if necessary, perform conversion of the signal
217 arguments to match the argument types of the slot.
218
219 To disconnect from a signal, you invoke the signal's
220 \c{disconnect()} function, passing the function to disconnect
221 as argument:
222
223 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 4
224
225 When a script function is invoked in response to a signal, the
226 \c this object will be the Global Object.
227
228 \section3 Signal to Member Function Connections
229
230 \c{connect(thisObject, function)}
231
232 In this form of the \c{connect()} function, the first argument
233 is the object that will be bound to the variable, \c this, when
234 the function specified using the second argument is invoked.
235
236 If you have a push button in a form, you typically want to do
237 something involving the form in response to the button's
238 \c{clicked} signal; passing the form as the \c this object
239 makes sense in such a case.
240
241 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 5
242
243 To disconnect from the signal, pass the same arguments to \c{disconnect()}:
244
245 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 6
246
247 \section3 Signal to Named Member Function Connections
248
249 \c{connect(thisObject, functionName)}
250
251 In this form of the \c{connect()} function, the first argument is
252 the object that will be bound to the variable, \c this, when
253 a function is invoked in response to the signal. The second argument
254 specifies the name of a function that is connected to the signal,
255 and this refers to a member function of the object passed as the
256 first argument (\c thisObject in the above scheme).
257
258 Note that the function is resolved when the connection is made, not
259 when the signal is emitted.
260
261 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 7
262
263 To disconnect from the signal, pass the same arguments to \c{disconnect()}:
264
265 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 8
266
267 \section3 Error Handling
268
269 When \c{connect()} or \c{disconnect()} succeeds, the function will
270 return \c{undefined}; otherwise, it will throw a script exception.
271 You can obtain an error message from the resulting \c{Error} object.
272 Example:
273
274 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 9
275
276 \section3 Emitting Signals from Scripts
277
278 To emit a signal from script code, you simply invoke the signal
279 function, passing the relevant arguments:
280
281 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 10
282
283 It is currently not possible to define a new signal in a script;
284 i.e., all signals must be defined by C++ classes.
285
286 \section3 Overloaded Signals and Slots
287
288 When a signal or slot is overloaded, QtScript will attempt to
289 pick the right overload based on the actual types of the QScriptValue arguments
290 involved in the function invocation. For example, if your class has slots \c{myOverloadedSlot(int)} and \c{myOverloadedSlot(QString)}, the following script code will behave reasonably:
291
292 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 11
293
294 You can specify a particular overload by using array-style property access with the \l{QMetaObject::normalizedSignature()}{normalized signature} of the C++ function as the property name:
295
296 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 12
297
298 If the overloads have different number of arguments, QtScript will
299 pick the overload with the argument count that best matches the
300 actual number of arguments passed to the slot.
301
302 For overloaded signals, Qt Script will throw an error if you try to connect
303 to the signal by name; you have to refer to the signal with the full
304 normalized signature of the particular overload you want to connect to.
305
306 \section2 Accessing Properties
307
308 The properties of the QObject are available as properties
309 of the corresponding QtScript object. When you manipulate
310 a property in script code, the C++ get/set method for that
311 property will automatically be invoked. For example, if your
312 C++ class has a property declared as follows:
313
314 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 13
315
316 then script code can do things like the following:
317
318 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 14
319
320 \section2 Accessing Child QObjects
321
322 Every named child of the QObject (that is, for which
323 QObject::objectName() is not an empty string) is by default available as
324 a property of the QtScript wrapper object. For example,
325 if you have a QDialog with a child widget whose \c{objectName} property is
326 \c{"okButton"}, you can access this object in script code through
327 the expression
328
329 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 15
330
331 Since \c{objectName} is itself a Q_PROPERTY, you can manipulate
332 the name in script code to, for example, rename an object:
333
334 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 16
335
336 You can also use the functions \c{findChild()} and \c{findChildren()}
337 to find children. These two functions behave identically to
338 QObject::findChild() and QObject::findChildren(), respectively.
339
340 For example, we can use these functions to find objects using strings
341 and regular expressions:
342
343 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 17
344
345 You typically want to use \c{findChild()} when manipulating a form
346 that uses nested layouts; that way the script is isolated from the
347 details about which particular layout a widget is located in.
348
349 \section2 Controlling QObject Ownership
350
351 Qt Script uses garbage collection to reclaim memory used by script
352 objects when they are no longer needed; an object's memory can be
353 automatically reclaimed when it is no longer referenced anywhere in
354 the scripting environment. Qt Script lets you control what happens
355 to the underlying C++ QObject when the wrapper object is reclaimed
356 (i.e., whether the QObject is deleted or not); you do this when you
357 create an object by passing an ownership mode as the second argument
358 to QScriptEngine::newQObject().
359
360 Knowing how Qt Script deals with ownership is important, since it can
361 help you avoid situations where a C++ object isn't deleted when it
362 should be (causing memory leaks), or where a C++ object \e{is}
363 deleted when it shouldn't be (typically causing a crash if C++ code
364 later tries to access that object).
365
366 \section3 Qt Ownership
367
368 By default, the script engine does not take ownership of the
369 QObject that is passed to QScriptEngine::newQObject(); the object
370 is managed according to Qt's object ownership (see
371 \l{Object Trees and Object Ownership}). This mode is appropriate
372 when, for example, you are wrapping C++ objects that are part of
373 your application's core; that is, they should persist regardless of
374 what happens in the scripting environment. Another way of stating
375 this is that the C++ objects should outlive the script engine.
376
377 \section3 Script Ownership
378
379 Specifying QScriptEngine::ScriptOwnership as the ownership mode
380 will cause the script engine to take full ownership of the QObject
381 and delete it when it determines that it is safe to do so
382 (i.e., when there are no more references to it in script code).
383 This ownership mode is appropriate if the QObject does not have a
384 parent object, and/or the QObject is created in the context of the
385 script engine and is not intended to outlive the script engine.
386
387 For example, a constructor function that constructs QObjects
388 only to be used in the script environment is a good candidate:
389
390 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 18
391
392 \section3 Auto-Ownership
393
394 With QScriptEngine::AutoOwnership the ownership is based on whether
395 the QObject has a parent or not.
396 If the QtScript garbage collector finds that the QObject is no
397 longer referenced within the script environment, the QObject will
398 be deleted \e{only} if it does not have a parent.
399
400 \section3 What Happens When Someone Else Deletes the QObject?
401
402 It is possible that a wrapped QObject is deleted outside of
403 Qt Script's control; i.e., without regard to the ownership mode
404 specified. In this case, the wrapper object will still
405 be an object (unlike the C++ pointer it wraps, the script object
406 won't become null). Any attempt to access properties of the script
407 object will, however, result in a script exception being thrown.
408
409 Note that QScriptValue::isQObject() will still return true for a
410 deleted QObject, since it tests the type of the script object, not
411 whether the internal pointer is non-null. In other words, if
412 QScriptValue::isQObject() returns true but QScriptValue::toQObject()
413 returns a null pointer, this indicates that the QObject has been
414 deleted outside of Qt Script (perhaps accidentally).
415
416 \section2 Customizing Access to the QObject
417
418 QScriptEngine::newQObject() can take a third argument which allows
419 you to control various aspects of the access to the QObject through
420 the QtScript wrapper object it returns.
421
422 QScriptEngine::ExcludeChildObjects specifies that child objects of
423 the QObject should not appear as properties of the wrapper object.
424
425 QScriptEngine::ExcludeSuperClassProperties and
426 QScriptEngine::ExcludeSuperClassMethods can be used to avoid
427 exposing members that are inherited from the QObject's superclass.
428 This is useful for defining a "pure" interface where inherited members
429 don't make sense from a scripting perspective; e.g., you don't want
430 script authors to be able to change the \c{objectName} property of
431 the object or invoke the \c{deleteLater()} slot.
432
433 QScriptEngine::AutoCreateDynamicProperties specifies that properties
434 that don't already exist in the QObject should be created as dynamic
435 properties of the QObject, rather than as properties of the QtScript
436 wrapper object. If you want new properties to truly become persistent
437 properties of the QObject, rather than properties that are destroyed
438 along with the wrapper object (and that aren't shared if the QObject
439 is wrapped multiple times with QScriptEngine::newQObject()), you
440 should use this option.
441
442 QScriptEngine::SkipMethodsInEnumeration specifies that signals and
443 slots should be skipped when enumerating the properties of the QObject
444 wrapper in a for-in script statement. This is useful when defining
445 prototype objects, since by convention function properties of
446 prototypes should not be enumerable.
447
448 \section2 Making a QObject-based Class New-able from a Script
449
450 The QScriptEngine::newQObject() function is used to wrap an
451 existing QObject instance, so that it can be made available to
452 scripts. A different scenario is that you want scripts to be
453 able to construct new objects, not just access existing ones.
454
455 The Qt meta-type system currently does not provide dynamic
456 binding of constructors for QObject-based classes. If you want to
457 make such a class new-able from scripts, Qt Script can generate
458 a reasonable script constructor for you; see
459 QScriptEngine::scriptValueFromQMetaObject().
460
461 You can also use QScriptEngine::newFunction() to wrap your own
462 factory function, and add it to the script environment; see
463 QScriptEngine::newQMetaObject() for an example.
464
465 \section2 Enum Values
466
467 Values for enums declared with Q_ENUMS are not available as
468 properties of individual wrapper objects; rather, they are
469 properties of the QMetaObject wrapper object that can be created
470 with QScriptEngine::newQMetaObject().
471
472 \section1 Conversion Between QtScript and C++ Types
473
474 QtScript will perform type conversion when a value needs to be
475 converted from the script side to the C++ side or vice versa; for
476 instance, when a C++ signal triggers a script function, when
477 you access a QObject property in script code, or when
478 you call QScriptEngine::toScriptValue() or
479 QScriptEngine::fromScriptValue() in C++. QtScript provides default
480 conversion operations for many of the built-in Qt types. You can
481 change the conversion operation for a type (including your custom
482 C++ types) by registering your own conversion functions with
483 qScriptRegisterMetaType().
484
485 \section2 Default Conversion from Qt Script to C++
486
487 The following table describes the default conversion from a
488 QScriptValue to a C++ type.
489
490 \table 80%
491 \header \o C++ Type \o Default Conversion
492 \row \o bool \o QScriptValue::toBool()
493 \row \o int \o QScriptValue::toInt32()
494 \row \o uint \o QScriptValue::toUInt32()
495 \row \o float \o float(QScriptValue::toNumber())
496 \row \o double \o QScriptValue::toNumber()
497 \row \o short \o short(QScriptValue::toInt32())
498 \row \o ushort \o QScriptValue::toUInt16()
499 \row \o char \o char(QScriptValue::toInt32())
500 \row \o uchar \o unsigned char(QScriptValue::toInt32())
501 \row \o qlonglong \o qlonglong(QScriptValue::toInteger())
502 \row \o qulonglong \o qulonglong(QScriptValue::toInteger())
503 \row \o QString \o An empty string if the QScriptValue is null
504 or undefined; QScriptValue::toString() otherwise.
505 \row \o QDateTime \o QScriptValue::toDateTime()
506 \row \o QDate \o QScriptValue::toDateTime().date()
507 \row \o QRegExp \o QScriptValue::toRegExp()
508 \row \o QObject* \o QScriptValue::toQObject()
509 \row \o QWidget* \o QScriptValue::toQObject()
510 \row \o QVariant \o QScriptValue::toVariant()
511 \row \o QChar \o If the QScriptValue is a string, the result
512 is the first character of the string, or a null QChar
513 if the string is empty; otherwise, the result is a QChar
514 constructed from the unicode obtained by converting the
515 QScriptValue to a \c{ushort}.
516 \row \o QStringList \o If the QScriptValue is an array, the
517 result is a QStringList constructed from the result of
518 QScriptValue::toString() for each array element; otherwise,
519 the result is an empty QStringList.
520 \row \o QVariantList \o If the QScriptValue is an array, the result
521 is a QVariantList constructed from the result of
522 QScriptValue::toVariant() for each array element; otherwise,
523 the result is an empty QVariantList.
524 \row \o QVariantMap \o If the QScriptValue is an object, the result
525 is a QVariantMap with a (key, value) pair of the form
526 (propertyName, propertyValue.toVariant()) for each property,
527 using QScriptValueIterator to iterate over the object's
528 properties.
529 \row \o QObjectList \o If the QScriptValue is an array, the result
530 is a QObjectList constructed from the result of
531 QScriptValue::toQObject() for each array element; otherwise,
532 the result is an empty QObjectList.
533 \row \o QList<int> \o If the QScriptValue is an array, the result is
534 a QList<int> constructed from the result of
535 QScriptValue::toInt32() for each array element; otherwise,
536 the result is an empty QList<int>.
537 \endtable
538
539 Additionally, QtScript will handle the following cases:
540
541 \list
542 \i If the QScriptValue is a QObject and the target type name ends with
543 \c * (i.e., it is a pointer), the QObject pointer will be cast to the
544 target type with qobject_cast().
545 \i If the QScriptValue is a QVariant and the target type name ends with
546 \c * (i.e., it is a pointer), and the \l{QVariant::userType()}{userType()}
547 of the QVariant is the type that the target type points to, the result
548 is a pointer to the QVariant's data.
549 \i If the QScriptValue is a QVariant and it can be converted to the
550 target type (according to QVariant::canConvert()), the QVariant will
551 be cast to the target type with qvariant_cast().
552 \endlist
553
554 \section2 Default Conversion from C++ to Qt Script
555
556 The following table describes the default behavior when a QScriptValue is
557 constructed from a C++ type:
558
559 \table 80%
560 \header \o C++ Type \o Default Construction
561 \row \o void \o QScriptEngine::undefinedValue()
562 \row \o bool \o QScriptValue(engine, value)
563 \row \o int \o QScriptValue(engine, value)
564 \row \o uint \o QScriptValue(engine, value)
565 \row \o float \o QScriptValue(engine, value)
566 \row \o double \o QScriptValue(engine, value)
567 \row \o short \o QScriptValue(engine, value)
568 \row \o ushort \o QScriptValue(engine, value)
569 \row \o char \o QScriptValue(engine, value)
570 \row \o uchar \o QScriptValue(engine, value)
571 \row \o QString \o QScriptValue(engine, value)
572 \row \o qlonglong \o QScriptValue(engine, qsreal(value)). Note that
573 the conversion may lead to loss of precision, since not all
574 64-bit integers can be represented using the qsreal type.
575 \row \o qulonglong \o QScriptValue(engine, qsreal(value)). Note that
576 the conversion may lead to loss of precision, since not all
577 64-bit unsigned integers can be represented using the qsreal
578 type.
579 \row \o QChar \o QScriptValue(this, value.unicode())
580 \row \o QDateTime \o \l{QScriptEngine::newDate()}{QScriptEngine::newDate}(value)
581 \row \o QDate \o \l{QScriptEngine::newDate()}{QScriptEngine::newDate}(value)
582 \row \o QRegExp \o \l{QScriptEngine::newRegExp()}{QScriptEngine::newRegExp}(value)
583 \row \o QObject* \o \l{QScriptEngine::newQObject()}{QScriptEngine::newQObject}(value)
584 \row \o QWidget* \o \l{QScriptEngine::newQObject()}{QScriptEngine::newQObject}(value)
585 \row \o QVariant \o \l{QScriptEngine::newVariant()}{QScriptEngine::newVariant}(value)
586 \row \o QStringList \o A new script array (created with
587 QScriptEngine::newArray()), whose elements are created using
588 the QScriptValue(QScriptEngine *, QString) constructor for
589 each element of the list.
590 \row \o QVariantList \o A new script array (created with
591 QScriptEngine::newArray()), whose elements are created using
592 QScriptEngine::newVariant() for each element of the list.
593 \row \o QVariantMap \o A new script object (created with
594 QScriptEngine::newObject()), whose properties are initialized
595 according to the (key, value) pairs of the map.
596 \row \o QObjectList \o A new script array (created with
597 QScriptEngine::newArray()), whose elements are created using
598 QScriptEngine::newQObject() for each element of the list.
599 \row \o QList<int> \o A new script array (created with
600 QScriptEngine::newArray()), whose elements are created using
601 the QScriptValue(QScriptEngine *, int) constructor for each
602 element of the list.
603 \endtable
604
605 Other types (including custom types) will be wrapped using
606 QScriptEngine::newVariant(). For null pointers of any type, the
607 result is QScriptEngine::nullValue().
608
609 \section1 How to Design and Implement Application Objects
610
611 This section explains how to implement application objects and
612 provides the necessary technical background material.
613
614 \section2 Making a C++ object available to Scripts Written in QtScript
615
616 Making C++ classes and objects available to a scripting language is
617 not trivial because scripting languages tend to be more dynamic than
618 C++, and it must be possible to introspect objects (query information
619 such as function names, function signatures, properties, etc., at
620 run-time). Standard C++ does not provide features for this.
621
622 We can achieve the functionality we want by extending C++, using
623 C++'s own facilities so our code is still standard C++. The Qt
624 meta-object system provides the necessary additional functionality.
625 It allows us to write using an extended C++ syntax, but converts this
626 into standard C++ using a small utility program called \l{moc}
627 (Meta-Object Compiler). Classes that wish to take advantage of the
628 meta-object facilities are either subclasses of QObject, or use the
629 \c{Q_OBJECT} macro. Qt has used this approach for many years and it has
630 proven to be solid and reliable. QtScript uses this meta-object
631 technology to provide scripters with dynamic access to C++ classes
632 and objects.
633
634 To completely understand how to make C++ objects available to Qt
635 Script, some basic knowledge of the Qt meta-object system is very
636 helpful. We recommend that you read the \l{Qt Object Model}. The
637 information in this document and the documents it links to are very
638 useful for understanding how to implement application objects.
639
640 However, this knowledge is not essential in the simplest cases.
641 To make an object available in QtScript, it must derive from
642 QObject. All classes which derive from QObject can be introspected
643 and can provide the information needed by the scripting engine at
644 run-time; e.g., class name, functions, signatures. Because we obtain
645 the information we need about classes dynamically at run-time, there
646 is no need to write wrappers for QObject derived classes.
647
648 \section2 Making C++ Class Member Functions Available in QtScript
649
650 The meta-object system also makes information about signals and slots
651 dynamically available at run-time. By default, for QObject subclasses,
652 only the signals and slots are automatically made available to scripts.
653 This is very convenient because, in practice, we normally only want to
654 make specially chosen functions available to scripters. When you create
655 a QObject subclass, make sure that the functions you want to expose to
656 QtScript are public slots.
657
658 For example, the following class definition enables scripting only for
659 certain functions:
660
661 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 19
662
663 In the example above, aNonScriptableFunction() is not declared as a
664 slot, so it will not be available in QtScript. The other three
665 functions will automatically be made available in QtScript because
666 they are declared in the \c{public slots} section of the class
667 definition.
668
669 It is possible to make any function script-invokable by specifying
670 the \c{Q_INVOKABLE} modifier when declaring the function:
671
672 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 20
673
674 Once declared with \c{Q_INVOKABLE}, the method can be invoked from
675 QtScript code just as if it were a slot. Although such a method is
676 not a slot, you can still specify it as the target function in a
677 call to \c{connect()} in script code; \c{connect()} accepts both
678 native and non-native functions as targets.
679
680 \section2 Making C++ Class Properties Available in QtScript
681
682 In the previous example, if we wanted to get or set a property using
683 QtScript we would have to write code like the following:
684
685 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 21
686
687 Scripting languages often provide a property syntax to modify and
688 retrieve properties (in our case the enabled state) of an
689 object. Many script programmers would want to write the above code
690 like this:
691
692 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 22
693
694 To make this possible, you must define properties in the C++ QObject
695 subclass. For example, the following \c MyObject class declaration
696 declares a boolean property called \c enabled, which uses the function
697 \c{setEnabled(bool)} as its setter function and \c{isEnabled()} as its
698 getter function:
699
700 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 23
701
702 The only difference from the original code is the use of the macro
703 \c{Q_PROPERTY}, which takes the type and name of the property, and
704 the names of the setter and getter functions as arguments.
705
706 If you don't want a property of your class to be accessible in
707 QtScript, you set the \c{SCRIPTABLE} attribute to \c false when
708 declaring the property; by default, the \c{SCRIPTABLE} attribute is
709 \c true. For example:
710
711 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 24
712
713 \section2 Reacting to C++ Objects Signals in Scripts
714
715 In the Qt object model, signals are used as a notification mechanism
716 between QObjects. This means one object can connect a signal to
717 another object's slot and, every time the signal is emitted, the slot
718 is called. This connection is established using the QObject::connect()
719 function.
720
721 The signals and slots mechanism is also available to QtScript
722 programmers. The code to declare a signal in C++ is the same,
723 regardless of whether the signal will be connected to a slot in C++
724 or in QtScript.
725
726 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 25
727
728 The only change we have made to the code in the previous section is
729 to declare a signals section with the relevant signal. Now, the
730 script writer can define a function and connect to the object like
731 this:
732
733 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 26
734
735 \section2 Design of Application Objects
736
737 The previous section described how to implement C++ objects which
738 can be used in QtScript. Application objects are the same kind of
739 objects, and they make your application's functionality available to
740 QtScript scripters. Since the C++ application is already written
741 in Qt, many objects are already QObjects. The easiest approach would
742 be to simply add all these QObjects as application objects to the
743 scripting engine. For small applications this might be sufficient,
744 but for larger applications this is probably not the right
745 approach. The problem is that this method reveals too much of the
746 internal API and gives script programmers access to application
747 internals which should not be exposed.
748
749 Generally, the best way of making application functionality available
750 to scripters is to code some QObjects which define the applications
751 public API using signals, slots, and properties. This gives you
752 complete control of the functionality made available by the
753 application. The implementations of these objects simply call the
754 functions in the application which do the real work. So, instead of
755 making all your QObjects available to the scripting engine, just add
756 the wrapper QObjects.
757
758 \section3 Returning QObject Pointers
759
760 If you have a slot that returns a QObject pointer, you should note
761 that, by default, Qt Script only handles conversion of the types
762 QObject* and QWidget*. This means that if your slot is declared
763 with a signature like "MyObject* getMyObject()", QtScript doesn't
764 automatically know that MyObject* should be handled in the same way
765 as QObject* and QWidget*. The simplest way to solve this is to only
766 use QObject* and QWidget* in the method signatures of your scripting
767 interface.
768
769 Alternatively, you can register conversion functions for your custom
770 type with the qScriptRegisterMetaType() function. In this way, you
771 can preserve the precise typing in your C++ declarations, while
772 still allowing pointers to your custom objects to flow seamlessly
773 between C++ and scripts. Example:
774
775 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 43
776
777 \section1 Function Objects and Native Functions
778
779 In Qt Script, functions are first-class values; they are objects that
780 can have properties of their own, just like any other type of
781 object. They can be stored in variables and passed as arguments to
782 other functions. Knowing how function calls in Qt Script behave is
783 useful when you want to define and use your own script functions.
784 This section discusses this matter, and also explains how you can
785 implement native functions; that is, Qt Script functions written in
786 C++, as opposed to functions written in the scripting language
787 itself. Even if you will be relying mostly on the dynamic QObject
788 binding that Qt Script provides, knowing about these powerful
789 concepts and techniques is important to understand what's actually
790 going on when script functions are executed.
791
792 \section2 Calling a Qt Script Function from C++
793
794 Calling a Qt Script function from C++ is achieved with the
795 QScriptValue::call() function. A typical scenario is that you evaluate a
796 script that defines a function, and at some point you want to call that
797 function from C++, perhaps passing it some arguments, and then handle the
798 result. The following script defines a Qt Script object that has a
799 toKelvin() function:
800
801 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 90
802
803 The toKelvin() function takes a temperature in Kelvin as argument, and
804 returns the temperature converted to Celsius. The following snippet shows
805 how the toKelvin() function might be obtained and called from C++:
806
807 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 91
808
809 If a script defines a global function, you can access the function as a
810 property of QScriptEngine::globalObject(). For example, the following script
811 defines a global function add():
812
813 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 56
814
815 C++ code might call the add() function as follows:
816
817 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 92
818
819 As already mentioned, functions are just values in Qt Script; a function by
820 itself is not "tied to" a particular object. This is why you have to specify
821 a \c{this} object (the first argument to QScriptValue::call()) that the
822 function should be applied to.
823
824 If the function is supposed to act as a method (i.e. it can only be applied
825 to a certain class of objects), it is up to the function itself to check
826 that it is being called with a compatible \c{this} object.
827
828 Passing an invalid QScriptValue as the \c{this} argument to
829 QScriptValue::call() indicates that the Global Object should be used as the
830 \c{this} object; in other words, that the function should be invoked as a
831 global function.
832
833 \section2 The \c this Object
834
835 When a Qt Script function is invoked from a script, the \e{way} in which it
836 is invoked determines the \c this object when the function body is executed,
837 as the following script example illustrates:
838
839 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 49
840
841 An important thing to note is that in Qt Script, unlike C++ and Java, the
842 \c this object is not part of the execution scope. This means that
843 member functions (i.e., functions that operate on \c this) must always
844 use the \c this keyword to access the object's properties. For example,
845 the following script probably doesn't do what you want:
846
847 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 50
848
849 You will get a reference error saying that 'a is not defined' or, worse,
850 two totally unrelated global variables \c a and \c b will be used to
851 perform the computation, if they exist. Instead, the script should look
852 like this:
853
854 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 51
855
856 Accidentally omitting the \c this keyword is a typical source of
857 error for programmers who are used to the scoping rules of C++ and Java.
858
859 \section2 Wrapping a Native Function
860
861 Qt Script provides QScriptEngine::newFunction() as a way of wrapping a
862 C++ function pointer; this enables you to implement a function in
863 C++ and add it to the script environment, so that scripts can invoke
864 your function as if it were a "normal" script function. Here is how the
865 previous \c{getProperty()} function can be written in C++:
866
867 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 52
868
869 Call QScriptEngine::newFunction() to wrap the function. This will
870 produce a special type of function object that carries a pointer to
871 the C++ function internally. Once the resulting wrapper has been
872 added to the scripting environment (e.g., by setting it as a property
873 of the Global Object), scripts can call the function without having
874 to know nor care that it is, in fact, a native function.
875
876 Note that the name of the C++ function doesn't matter in the
877 scripting sense; the name by which the function is invoked by
878 scripts depends only on what you call the script object property
879 in which you store the function wrapper.
880
881 It is currently not possible to wrap member functions; i.e., methods
882 of a C++ class that require a \c this object.
883
884 \section2 The QScriptContext Object
885
886 A QScriptContext holds all the state associated with a particular
887 invocation of your function. Through the QScriptContext, you can:
888 \list
889 \i Get the arguments that were passed to the function.
890 \i Get the \c this object.
891 \i Find out whether the function was called with the \c new operator
892 (the significance of this will be explained later).
893 \i Throw a script error.
894 \i Get the function object that's being invoked.
895 \i Get the activation object (the object used to hold local variables).
896 \endlist
897
898 The following sections explain how to make use of this
899 functionality.
900
901 \section2 Processing Function Arguments
902
903 Two things are worth noting about function arguments:
904
905 \list 1
906 \o Any script function \mdash including native functions \mdash can
907 be invoked with any number of arguments. This means that it is up to
908 the function itself to check the argument count if necessary, and act
909 accordingly (e.g., throw an error if the number of arguments is
910 too large, or prepare a default value if the number is too small).
911 \o A value of any type can be supplied as an argument to any
912 function. This means that it is up to you to check the type of the
913 arguments if necessary, and act accordingly (e.g., throw an error
914 if an argument is not an object of a certain type).
915 \endlist
916
917 In summary: Qt Script does not automatically enforce any constraints on the
918 number or type of arguments involved in a function call.
919
920 \section3 Formal Parameters and the Arguments Object
921
922 A native Qt Script function is analogous to a script function that defines no
923 formal parameters and only uses the built-in \c arguments variable to
924 process its arguments. To see this, let's first consider how a
925 script would normally define an \c{add()} function that takes two
926 arguments, adds them together and returns the result:
927
928 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 56
929
930 When a script function is defined with formal parameters, their
931 names can be viewed as mere aliases of properties of the \c
932 arguments object; for example, in the \c{add(a, b)} definition's
933 function body, \c a and \c arguments[0] refer to the same
934 variable. This means that the \c{add()} function can equivalently be
935 written like this:
936
937 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 57
938
939 This latter form closely matches what a native implementation
940 typically looks like:
941
942 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 58
943
944 \section3 Checking the Number of Arguments
945
946 Again, remember that the presence (or lack) of formal parameter
947 names in a function definition does not affect how the function
948 may be invoked; \c{add(1, 2, 3)} is allowed by the engine, as is
949 \c{add(42)}. In the case of the \c {add()} function, the function
950 really needs two arguments in order to do something useful. This
951 can be expressed by the script definition as follows:
952
953 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 59
954
955 This would result in an error being thrown if a script invokes
956 \c{add()} with anything other than two arguments. The native
957 function can be modified to perform the same check:
958
959 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 62
960
961 \section3 Checking the Types of Arguments
962
963 In addition to expecting a certain number of arguments, a function might
964 expect that those arguments are of certain types (e.g., that the first
965 argument is a number and that the second is a string). Such a function
966 should explicitly check the type of arguments and/or perform a conversion,
967 or throw an error if the type of an argument is incompatible.
968
969 As it is, the native implementation of \c{add()} shown above doesn't
970 have the exact same semantics as the script counterpart; this is
971 because the behavior of the Qt Script \c{+} operator depends on the
972 types of its operands (for example, if one of the operands is a string,
973 string concatenation is performed). To give the script function
974 stricter semantics (namely, that it should only add numeric
975 operands), the argument types can be tested:
976
977 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 60
978
979 Then an invocation like \c{add("foo", new Array())} will
980 cause an error to be thrown.
981
982 The C++ version can call QScriptValue::isNumber() to perform similar
983 tests:
984
985 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 63
986
987 A less strict script implementation might settle for performing an
988 explicit to-number conversion before applying the \c{+} operator:
989
990 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 61
991
992 In a native implementation, this is equivalent to calling
993 QScriptValue::toNumber() without performing any type test first,
994 since QScriptValue::toNumber() will automatically perform a type
995 conversion if necessary.
996
997 To check if an argument is of a certain object type (class),
998 scripts can use the \c instanceof operator (e.g., \c{"arguments[0]
999 instanceof Array"} evaluates to true if the first argument is an
1000 Array object); native functions can call QScriptValue::instanceOf().
1001
1002 To check if an argument is of a custom C++ type, you typically use
1003 qscriptvalue_cast() and check if the result is valid. For object types,
1004 this means casting to a pointer and checking if it is non-zero; for
1005 value types, the class should have an \c{isNull()}, \c{isValid()}
1006 or similar method. Alternatively, since most custom types are
1007 transported in \l{QVariant}s, you can check if the script value is a
1008 QVariant using QScriptValue::isVariant(), and then check if the
1009 QVariant can be converted to your type using QVariant::canConvert().
1010
1011 \section3 Functions with Variable Numbers of Arguments
1012
1013 Because of the presence of the built-in \c arguments object,
1014 implementing functions that take a variable number of arguments
1015 is simple. In fact, as we have seen, in the technical sense \e{all}
1016 Qt Script functions can be seen as variable-argument functions).
1017 As an example, consider a concat() function that takes an arbitrary
1018 number of arguments, converts the arguments to their string
1019 representation and concatenates the results; for example,
1020 \c{concat("Qt", " ", "Script ", 101)} would return "Qt Script 101".
1021 A script definition of \c{concat()} might look like this:
1022
1023 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 64
1024
1025 Here is an equivalent native implementation:
1026
1027 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 65
1028
1029 A second use case for a variable number of arguments is to implement
1030 optional arguments. Here's how a script definition typically does
1031 it:
1032
1033 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 66
1034
1035 And here's the native equivalent:
1036
1037 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 67
1038
1039 A third use case for a variable number of arguments is to simulate
1040 C++ overloads. This involves checking the number of arguments and/or
1041 their type at the beginning of the function body (as already shown),
1042 and acting accordingly. It might be worth thinking twice before
1043 doing this, and instead favor unique function names; e.g., having
1044 separate \c{processNumber(number)} and \c{processString(string)}
1045 functions rather than a generic \c{process(anything)} function.
1046 On the caller side, this makes it harder for scripts to accidentally
1047 call the wrong overload (since they don't know or don't comprehend
1048 your custom sophisticated overloading resolution rules), and on the
1049 callee side, you avoid the need for potentially complex (read:
1050 error-prone) checks to resolve ambiguity.
1051
1052 \section3 Accessing the Arguments Object
1053
1054 Most native functions use the QScriptContext::argument() function to
1055 access function arguments. However, it is also possible to access
1056 the built-in \c arguments object itself (the one referred to by the
1057 \c arguments variable in script code), by calling the
1058 QScriptContext::argumentsObject() function. This has three principal
1059 applications:
1060
1061 \list
1062 \o The \c arguments object can be used to easily forward a function
1063 call to another function. In script code, this is what it
1064 typically looks like:
1065
1066 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 68
1067
1068 For example, \c{foo(10, 20, 30)} would result in the \c{foo()} function
1069 executing the equivalent of \c{bar(10, 20, 30)}. This is useful if
1070 you want to perform some special pre- or post-processing when
1071 calling a function (e.g., to log the call to \c{bar()} without having
1072 to modify the \c{bar()} function itself, like the above example), or if
1073 you want to call a "base implementation" from a prototype
1074 function that has the exact same "signature". In C++, the forwarding
1075 function might look like this:
1076
1077 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 69
1078
1079 \o The arguments object can serve as input to a QScriptValueIterator,
1080 providing a generic way to iterate over the arguments. A debugger
1081 might use this to display the arguments object in a general purpose
1082 "Qt Script Object Explorer", for example.
1083
1084 \o The arguments object can be serialized (e.g., with JSON) and transferred
1085 to another entity (e.g., a script engine running in another thread),
1086 where the object can be deserialized and passed as argument to
1087 another script function.
1088 \endlist
1089
1090 \section2 Constructor Functions
1091
1092 Some script functions are constructors; they are expected to initialize
1093 new objects. The following snippet is a small example:
1094
1095 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 75
1096
1097 There is nothing special about constructor functions. In fact, any
1098 script function can act as a constructor function (i.e., any function
1099 can serve as the operand to \c{new}). Some functions behave differently
1100 depending on whether they are called as part of a \c{new} expression
1101 or not; for example, the expression \c{new Number(1)} will create a
1102 Number object, whereas \c{Number("123")} will perform a type
1103 conversion. Other functions, like \c{Array()}, will always create
1104 and initialize a new object (e.g., \c{new Array()} and \c{Array()} have
1105 the same effect).
1106
1107 A native Qt Script function can call the
1108 QScriptContext::isCalledAsConstructor() function to determine if it
1109 is being called as a constructor or as a regular function. When a
1110 function is called as a constructor (i.e., it is the operand in a
1111 \c{new} expression), this has two important implications:
1112
1113 \list
1114 \i The \c this object, QScriptContext::thisObject(), contains
1115 the new object to be initialized; the engine creates this
1116 new object automatically before invoking your function. This means
1117 that your native constructor function normally doesn't have to (and
1118 shouldn't) create a new object when it is called as a
1119 constructor, since the engine has already prepared a new
1120 object. Instead your function should operate on the supplied
1121 \c this object.
1122 \i The constructor function should return an undefined value,
1123 QScriptEngine::undefinedValue(), to tell the engine that the
1124 \c this object should be the final result of the \c new
1125 operator. Alternatively, the function can return the \c this
1126 object itself.
1127 \endlist
1128
1129 When QScriptContext::isCalledAsConstructor() returns false, how your
1130 constructor handles this case depends on what behavior you desire.
1131 If, like the built-in \c{Number()} function, a plain function call should
1132 perform a type conversion of its argument, then you perform the conversion
1133 and return the result. If, on the other hand, you want your constructor
1134 to behave \e{as if it was called as a constructor} (with
1135 \c{new}), you have to explicitly create a new object (that is,
1136 ignore the \c this object), initialize that object, and return it.
1137
1138 The following example implements a constructor function that always
1139 creates and initializes a new object:
1140
1141 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 76
1142
1143 Given this constructor, scripts would be able to use either the
1144 expression \c{new Person("Bob")} or \c{Person("Bob")} to create a
1145 new \c{Person} object; both behave in the same way.
1146
1147 There is no equivalent way for a function defined in script
1148 code to determine whether or not it was invoked as a constructor.
1149
1150 Note that, even though it is not considered good practice, there is
1151 nothing that stops you from choosing to ignore the default
1152 constructed (\c this) object when your function is called as a
1153 constructor and creating your own object anyway; simply have the
1154 constructor return that object. The object will "override" the
1155 default object that the engine constructed (i.e., the default
1156 object will simply be discarded internally).
1157
1158 \section2 Associating Data with a Function
1159
1160 Even if a function is global \mdash i.e., not associated with any particular
1161 (type of) object \mdash you might still want to associate some data with it,
1162 so that it becomes self-contained; for example, the function could have
1163 a pointer to some C++ resource that it needs to access. If your application
1164 only uses a single script engine, or the same C++ resource can/should be
1165 shared among all script engines, you can simply use a static C++ variable
1166 and access it from within the native Qt Script function.
1167
1168 In the case where a static C++ variable or singleton class is
1169 not appropriate, you can call QScriptValue::setProperty() on the
1170 function object, but be aware that those properties will also be
1171 accessible to script code. The alternative is to use QScriptValue::setData();
1172 this data is not script-accessible. The implementation can access this
1173 internal data through the QScriptContext::callee() function, which
1174 returns the function object being invoked. The following example
1175 shows how this might be used:
1176
1177 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 55
1178
1179 \section2 Native Functions as Arguments to Functions
1180
1181 As previously mentioned, a function object can be passed as argument
1182 to another function; this is also true for native functions,
1183 naturally. As an example, here's a native comparison function
1184 that compares its two arguments numerically:
1185
1186 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 53
1187
1188 The above function can be passed as argument to the standard
1189 \c{Array.prototype.sort} function to sort an array numerically,
1190 as the following C++ code illustrates:
1191
1192 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 54
1193
1194 Note that, in this case, we are truly treating the native function
1195 object as a value \mdash i.e., we don't store it as a property of the
1196 scripting environment \mdash we simply pass it on as an "anonymous"
1197 argument to another script function and then forget about it.
1198
1199 \section2 The Activation Object
1200
1201 Every Qt Script function invocation has an \e{activation object}
1202 associated with it; this object is accessible through the
1203 QScriptContext::activationObject() function. The activation object
1204 is a script object whose properties are the local variables
1205 associated with the invocation (including the arguments for which
1206 the script function has a corresponding formal parameter name).
1207 Thus, getting, modifying, creating and deleting local variables
1208 from C++ is done using the regular QScriptValue::property() and
1209 QScriptValue::setProperty() functions. The activation object itself
1210 is not directly accessible from script code (but it is implicitly
1211 accessed whenever a local variable is read from or written to).
1212
1213 For C++ code, there are two principal applications of the
1214 activation object:
1215
1216 \list
1217 \i The activation object provides a standard way to traverse the
1218 variables associated with a function call, by using it as the input
1219 to QScriptValueIterator. This is useful for debugging purposes.
1220
1221 \i The activation object can be used to prepare local variables
1222 that should be available when a script is evaluated inline; this
1223 can be viewed as a way of passing arguments to the script
1224 itself. This technique is typically used in conjunction with
1225 QScriptEngine::pushContext(), as in the following example:
1226
1227 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 77
1228
1229 We create a temporary execution context, create a local variable
1230 for it, evaluate the script, and finally restore the old context.
1231 \endlist
1232
1233 \section2 Nested Functions and the Scope Chain
1234
1235 This is an advanced topic; feel free to skip it.
1236
1237 A nested function can be used to "capture" the execution context in which a
1238 nested function object is created; this is typically referred to as creating
1239 a \e closure. When, at some later time, the nested function is invoked, it
1240 can access the variables that were created when the enclosing function was
1241 invoked. This can perhaps best be illustrated through a small example:
1242
1243 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 70
1244
1245 The \c{counter()} function initializes a local variable to zero,
1246 and returns a nested function. The nested function increments
1247 the "outer" variable and returns its new value. The variable
1248 persists over function calls, as shown in the following example:
1249
1250 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 71
1251
1252 The \c{counter()} function can be implemented as a native function, too
1253 \mdash or rather, as a pair of native functions: One for the outer and
1254 one for the inner. The definition of the outer function is as follows:
1255
1256 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 72
1257
1258 The function creates a local variable and initializes it to zero.
1259 Then it wraps the inner native function, and sets the scope of
1260 the resulting function object to be the activation object associated
1261 with this (the outer) function call. The inner function accesses
1262 the "outer" activation through the scope of the callee:
1263
1264 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 73
1265
1266 It is also possible to have a hybrid approach, where the outer function
1267 is a native function and the inner function is defined by a script:
1268
1269 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 74
1270
1271 \section2 Property Getters and Setters
1272
1273 A script object property can be defined in terms of a getter/setter
1274 function, similar to how a Qt C++ property has read and write
1275 functions associated with it. This makes it possible for a script to
1276 use expressions like \c{object.x} instead of \c{object.getX()}; the
1277 getter/setter function for \c{x} will implicitly be invoked
1278 whenever the property is accessed. To scripts, the property looks
1279 and behaves just like a regular object property.
1280
1281 A single Qt Script function can act as both getter and setter for
1282 a property. When it is called as a getter, the argument count is 0.
1283 When it is called as a setter, the argument count is 1; the argument
1284 is the new value of the property. In the following example, we
1285 define a native combined getter/setter that transforms the value
1286 slightly:
1287
1288 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 78
1289
1290 The example uses the internal data of the object to store and
1291 retrieve the transformed value. Alternatively, the property
1292 could be stored in another, "hidden" property of the object itself
1293 (e.g., \c{__x__}). A native function is free to implement whatever
1294 storage scheme it wants, as long as the external behavior of the
1295 property itself is consistent (e.g., that scripts should not be able
1296 to distinguish it from a regular property).
1297
1298 The following C++ code shows how an object property can be defined
1299 in terms of the native getter/setter:
1300
1301 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 79
1302
1303 When the property is accessed, like in the following script, the
1304 getter/setter does its job behind the scenes:
1305
1306 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 80
1307
1308 \note It is important that the setter function, not just the getter,
1309 returns the value of the property; i.e., the setter should \e{not}
1310 return QScriptValue::UndefinedValue. This is because the result of
1311 the property assignment is the value returned by the setter, and
1312 not the right-hand side expression. Also note that you normally
1313 should not attempt to read the same property that the getter modifies
1314 within the getter itself, since this will cause the getter to be
1315 called recursively.
1316
1317 You can remove a property getter/setter by calling
1318 QScriptValue::setProperty(), passing an invalid QScriptValue
1319 as the getter/setter. Remember to specify the
1320 QScriptValue::PropertyGetter/QScriptValue::PropertySetter flag(s),
1321 otherwise the only thing that will happen is that the setter will be
1322 invoked with an invalid QScriptValue as its argument!
1323
1324 Property getters and setters can be defined and installed by script
1325 code as well, as in the following example:
1326
1327 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 81
1328
1329 Getters and setters can only be used to implement "a priori
1330 properties"; i.e., the technique can't be used to react to an access
1331 to a property that the object doesn't already have. To gain total
1332 control of property access in this way, you need to subclass
1333 QScriptClass.
1334
1335 \section1 Making Use of Prototype-Based Inheritance
1336
1337 In ECMAScript, inheritance is based on the concept of \e{shared
1338 prototype objects}; this is quite different from the class-based
1339 inheritance familiar to C++ programmers. With QtScript, you can
1340 associate a custom prototype object with a C++ type using
1341 QScriptEngine::setDefaultPrototype(); this is the key to providing
1342 a script interface to that type. Since the QtScript module is built
1343 on top of Qt's meta-type system, this can be done for any C++ type.
1344
1345 You might be wondering when exactly you would need to use this
1346 functionality in your application; isn't the automatic binding
1347 provided by QScriptEngine::newQObject() enough? No, not under all
1348 circumstances.
1349 Firstly, not every C++ type is derived from QObject; types that
1350 are not QObjects cannot be introspected through Qt's meta-object
1351 system (they do not have properties, signals and slots). Secondly,
1352 even if a type is QObject-derived, the functionality you want to
1353 expose to scripts might not all be available, since it is unusual to
1354 define every function to be a slot (and it's not always
1355 possible/desirable to change the C++ API to make it so).
1356
1357 It is perfectly possible to solve this problem by using "conventional"
1358 C++ techniques. For instance, the QRect class could effectively be
1359 made scriptable by creating a QObject-based C++ wrapper class with
1360 \c{x}, \c{y}, \c{width} properties and so on, which forwarded property
1361 access and function calls to the wrapped value. However, as we shall
1362 see, by taking advantage of the ECMAScript object model and combining
1363 it with Qt's meta-object system, we can arrive at a solution that is
1364 more elegant, consistent and lightweight, supported by a small API.
1365
1366 This section explains the underlying concepts of prototype-based
1367 inheritance. Once these concepts are understood, the associated
1368 practices can be applied throughout the QtScript API in order to
1369 create well-behaved, consistent bindings to C++ that will fit nicely
1370 into the ECMAScript universe.
1371
1372 When experimenting with QtScript objects and inheritance, it can be
1373 helpful to use the interactive interpreter included with the
1374 \l{Qt Examples#Qt Script}{Qt Script examples}, located in
1375 \c{examples/script/qscript}.
1376
1377 \section2 Prototype Objects and Shared Properties
1378
1379 The purpose of a QtScript \e{prototype object} is to define
1380 behavior that should be shared by a set of other QtScript
1381 objects. We say that objects which share the same prototype object
1382 belong to the same \e{class} (again, on the technical side this
1383 should not to be confused with the class constructs of languages
1384 like C++ and Java; ECMAScript has no such construct).
1385
1386 The basic prototype-based inheritance mechanism works as follows: Each
1387 QtScript object has an internal link to another object, its
1388 \e{prototype}. When a property is looked up in an object, and the
1389 object itself does not have the property, the property is looked up
1390 in the prototype object instead; if the prototype has the property,
1391 then that property is returned. Otherwise, the property is looked up
1392 in the prototype of the prototype object, and so on; this chain of
1393 objects constitutes a \e{prototype chain}. The chain of prototype
1394 objects is followed until the property is found or the end of the
1395 chain is reached.
1396
1397 For example, when you create a new object by the expression \c{new
1398 Object()}, the resulting object will have as its prototype the
1399 standard \c{Object} prototype, \c{Object.prototype}; through this
1400 prototype relation, the new object inherits a set of properties,
1401 including the \c{hasOwnProperty()} function and \c{toString()}
1402 function:
1403
1404 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 27
1405
1406 The \c{toString()} function itself is not defined in \c{o} (since we
1407 did not assign anything to \c{o.toString}), so instead the
1408 \c{toString()} function in the standard \c{Object} prototype is
1409 called, which returns a highly generic string representation of
1410 \c{o} ("[object Object]").
1411
1412 Note that the properties of the prototype object are not \e{copied} to
1413 the new object; only a \e{link} from the new object to the prototype
1414 object is maintained. This means that changes done to the prototype
1415 object will immediately be reflected in the behavior of all objects
1416 that have the modified object as their prototype.
1417
1418 \section2 Defining Classes in a Prototype-Based Universe
1419
1420 In QtScript, a class is not defined explicitly; there is no
1421 \c{class} keyword. Instead, you define a new class in two steps:
1422
1423 \list 1
1424 \i Define a \e{constructor function} that will initialize new objects.
1425 \i Set up a \e{prototype object} that defines the class interface, and
1426 assign this object to the public \c{prototype} property of the
1427 constructor function.
1428 \endlist
1429
1430 With this arrangement, the constructor's public \c{prototype}
1431 property will automatically be set as the prototype of objects created
1432 by applying the \c{new} operator to your constructor function;
1433 e.g., the prototype of an object created by \c{new Foo()} will be the
1434 value of \c{Foo.prototype}.
1435
1436 Functions that don't operate on the \c this object ("static" methods)
1437 are typically stored as properties of the constructor function, not
1438 as properties of the prototype object. The same is true for
1439 constants, such as enum values.
1440
1441 The following code defines a simple constructor function for a class
1442 called \c{Person}:
1443
1444 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 28
1445
1446 Next, you want to set up \c{Person.prototype} as your prototype
1447 object; i.e., define the interface that should be common to all
1448 \c{Person} objects. QtScript automatically creates a default
1449 prototype object (by the expression \c{new Object()}) for every
1450 script function; you can add properties to this object, or you can
1451 assign your own custom object. (Generally speaking, any QtScript
1452 object can act as prototype for any other object.)
1453
1454 Here's an example of how you might want to override the
1455 \c{toString()} function that \c{Person.prototype} inherits from
1456 \c{Object.prototype}, to give your \c{Person} objects a more
1457 appropriate string representation:
1458
1459 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 29
1460
1461 This resembles the process of reimplementing a virtual function
1462 in C++. Henceforth, when the property named \c{toString} is
1463 looked up in a \c{Person} object, it will be resolved in
1464 \c{Person.prototype}, not in \c{Object.prototype} as before:
1465
1466 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 30
1467
1468 There are also some other interesting things we can learn about a
1469 \c{Person} object:
1470
1471 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 31
1472
1473 The \c{hasOwnProperty()} function is not inherited from
1474 \c{Person.prototype}, but rather from \c{Object.prototype}, which is
1475 the prototype of \c{Person.prototype} itself; i.e., the prototype
1476 chain of \c{Person} objects is \c{Person.prototype} followed by
1477 \c{Object.prototype}. This prototype chain establishes a \e{class
1478 hierarchy}, as demonstrated by applying the \c{instanceof} operator;
1479 \c{instanceof} checks if the value of the public \c{prototype}
1480 property of the constructor function on the right-hand side is
1481 reached by following the prototype chain of the object on the
1482 left-hand side.
1483
1484 When defining subclasses, there's a general pattern you can use. The
1485 following example shows how one can create a subclass of \c{Person}
1486 called \c{Employee}:
1487
1488 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 32
1489
1490 Again, you can use the \c{instanceof} to verify that the
1491 class relationship between \c{Employee} and \c{Person} has been
1492 correctly established:
1493
1494 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 33
1495
1496 This shows that the prototype chain of \c{Employee} objects is the
1497 same as that of \c{Person} objects, but with \c{Employee.prototype}
1498 added to the front of the chain.
1499
1500 \section2 Prototype-Based Programming with the QtScript C++ API
1501
1502 You can use QScriptEngine::newFunction() to wrap
1503 native functions. When implementing a constructor function,
1504 you also pass the prototype object as an argument to
1505 QScriptEngine::newFunction().
1506 You can call QScriptValue::construct() to call a constructor
1507 function, and you can use QScriptValue::call() from within a
1508 native constructor function if you need to call a base class
1509 constructor.
1510
1511 The QScriptable class provides a convenient way to implement a
1512 prototype object in terms of C++ slots and properties. Take a look
1513 at the \l{Default Prototypes Example} to see how this is done.
1514 Alternatively, the prototype functionality can be implemented in
1515 terms of standalone native functions that you wrap with
1516 QScriptEngine::newFunction() and set as properties of your prototype
1517 object by calling QScriptValue::setProperty().
1518
1519 In the implementation of your prototype functions, you use
1520 QScriptable::thisObject() (or QScriptContext::thisObject()) to
1521 obtain a reference to the QScriptValue being operated upon; then you
1522 call qscriptvalue_cast() to cast it to your C++ type, and perform
1523 the relevant operations using the usual C++ API for the type.
1524
1525 You associate a prototype object with a C++ type by calling
1526 QScriptEngine::setDefaultPrototype(). Once this mapping is
1527 established, QtScript will automatically assign the correct
1528 prototype when a value of such a type is wrapped in a QScriptValue;
1529 either when you explicitly call QScriptEngine::toScriptValue(), or
1530 when a value of such a type is returned from a C++ slot and
1531 internally passed back to script code by the engine. This means you
1532 \e{don't} have to implement wrapper classes if you use this
1533 approach.
1534
1535 As an example, let's consider how the \c{Person} class from the
1536 preceding section can be implemented in terms of the Qt Script API.
1537 We begin with the native constructor function:
1538
1539 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 34
1540
1541 Here's the native equivalent of the \c{Person.prototype.toString}
1542 function we saw before:
1543
1544 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 35
1545
1546 The \c{Person} class can then be initialized as follows:
1547
1548 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 36
1549
1550 The implementation of the \c{Employee} subclass is similar. We
1551 use QScriptValue::call() to call the super-class (Person) constructor:
1552
1553 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 37
1554
1555 The \c{Employee} class can then be initialized as follows:
1556
1557 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 38
1558
1559 When implementing the prototype object of a class, you may want to use
1560 the QScriptable class, as it enables you to define the API of your
1561 script class in terms of Qt properties, signals and slots, and
1562 automatically handles value conversion between the Qt Script and C++
1563 side.
1564
1565 \section2 Implementing Prototype Objects for Value-based Types
1566
1567 When implementing a prototype object for a value-based type --
1568 e.g. QPointF -- the same general technique applies; you populate
1569 a prototype object with functionality that should be shared
1570 among instances. You then associate the prototype object with
1571 the type by calling QScriptEngine::setDefaultPrototype(). This
1572 ensures that when e.g. a value of the relevant type is returned
1573 from a slot back to the script, the prototype link of the script
1574 value will be initialized correctly.
1575
1576 When values of the custom type are stored in QVariants -- which Qt
1577 Script does by default --, qscriptvalue_cast() enables you to safely
1578 cast the script value to a pointer to the C++ type. This makes it
1579 easy to do type-checking, and, for prototype functions that should
1580 modify the underlying C++ value, lets you modify the actual value
1581 contained in the script value (and not a copy of it).
1582
1583 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 39
1584
1585 \section2 Implementing Constructors for Value-based Types
1586
1587 You can implement a constructor function for a value-based type
1588 by wrapping a native factory function. For example, the following
1589 function implements a simple constructor for QPoint:
1590
1591 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 44
1592
1593 In the above code we simplified things a bit, e.g. we didn't check
1594 the argument count to decide which QPoint C++ constructor to use.
1595 In your own constructors you have to do this type of resolution
1596 yourself, i.e. by checking the number of arguments passed to the
1597 native function, and/or by checking the type of the arguments and
1598 converting the arguments to the desired type. If you detect a problem
1599 with the arguments you may want to signal this by throwing a script
1600 exception; see QScriptContext::throwError().
1601
1602 \section2 Managing Non-QObject-based Objects
1603
1604 For value-based types (e.g. QPoint), the C++ object will be destroyed when
1605 the Qt Script object is garbage-collected, so managing the memory of the C++
1606 object is not an issue. For QObjects, Qt Script provides several
1607 alternatives for managing the underlying C++ object's lifetime; see the
1608 \l{Controlling QObject Ownership} section. However, for polymorphic types
1609 that don't inherit from QObject, and when you can't (or won't) wrap the type
1610 in a QObject, you have to manage the lifetime of the C++ object yourself.
1611
1612 A behavior that's often reasonable when a Qt Script object wraps a C++
1613 object, is that the C++ object is deleted when the Qt Script object is
1614 garbage-collected; this is typically the case when the objects can be
1615 constructed by scripts, as opposed to the application providing the scripts
1616 with pre-made "environment" objects. A way of making the lifetime of the C++
1617 object follow the lifetime of the Qt Script object is by using a shared
1618 pointer class, such as QSharedPointer, to hold a pointer to your object;
1619 when the Qt Script object containing the QSharedPointer is
1620 garbage-collected, the underlying C++ object will be deleted if there are no
1621 other references to the object.
1622
1623 The following snippet shows a constructor function that constructs
1624 QXmlStreamReader objects that are stored using QSharedPointer:
1625
1626 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 93
1627
1628 Prototype functions can use qscriptvalue_cast() to cast the \c this object
1629 to the proper type:
1630
1631 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 94
1632
1633 The prototype and constructor objects are set up in the usual way:
1634
1635 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 95
1636
1637 Scripts can now construct QXmlStreamReader objects by calling the \c
1638 XmlStreamReader constructor, and when the Qt Script object is
1639 garbage-collected (or the script engine is destroyed), the QXmlStreamReader
1640 object is destroyed as well.
1641
1642 \section1 Defining Custom Script Classes with QScriptClass
1643
1644 There are cases where neither the dynamic QObject binding provided
1645 by QScriptEngine::newQObject() or the manual binding provided by
1646 QScriptEngine::newFunction() is sufficient. For example, you might
1647 want to implement a dynamic script proxy to an underlying object;
1648 or you might want to implement an array-like class (i.e. that gives
1649 special treatment to properties that are valid array indexes, and
1650 to the property "length"). In such cases, you can subclass
1651 QScriptClass to achieve the desired behavior.
1652
1653 QScriptClass allows you to handle all property access for a
1654 (class of) script object through virtual get/set property functions.
1655 Iteration of custom properties is also supported through the
1656 QScriptClassPropertyIterator class; this means you can advertise
1657 properties to be reported by for-in script statements and
1658 QScriptValueIterator.
1659
1660 \section1 Error Handling and Debugging Facilities
1661
1662 Syntax errors in scripts will be reported as soon as a script is
1663 evaluated; QScriptEngine::evaluate() will return a SyntaxError object
1664 that you can convert to a string to get a description of the error.
1665
1666 The QScriptEngine::uncaughtExceptionBacktrace() function gives you
1667 a human-readable backtrace of the last uncaught exception. In order
1668 to get useful filename information in backtraces, you should pass
1669 proper filenames to QScriptEngine::evaluate() when evaluating your
1670 scripts.
1671
1672 Often an exception doesn't happen at the time the script is evaluated,
1673 but at a later time when a function defined by the script is actually
1674 executed. For C++ signal handlers, this is tricky; consider the case
1675 where the clicked() signal of a button is connected to a script function,
1676 and that script function causes a script exception when it is handling
1677 the signal. Where is that script exception propagated to?
1678
1679 The solution is to connect to the QScriptEngine::signalHandlerException()
1680 signal; this will give you notification when a signal handler causes
1681 an exception, so that you can find out what happened and/or recover
1682 from it.
1683
1684 In Qt 4.4 the QScriptEngineAgent class was introduced. QScriptEngineAgent
1685 provides an interface for reporting low-level "events" in a script engine,
1686 such as when a function is entered or when a new script statement is
1687 reached. By subclassing QScriptEngineAgent you can be notified of these
1688 events and perform some action, if you want. QScriptEngineAgent itself
1689 doesn't provide any debugging-specific functionality (e.g. setting
1690 breakpoints), but it is the basis of tools that do.
1691
1692 The QScriptEngineDebugger class introduced in Qt 4.5 provides a Qt Script
1693 debugger that can be embedded into your application.
1694
1695 \section2 Redefining print()
1696
1697 Qt Script provides a built-in print() function that can be useful for
1698 simple debugging purposes. The built-in print() function writes to
1699 standard output. You can redefine the print() function (or add your
1700 own function, e.g. debug() or log()) that redirects the text to
1701 somewhere else. The following code shows a custom print() that adds
1702 text to a QPlainTextEdit.
1703
1704 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 45
1705
1706 The following code shows how the custom print() function may be
1707 initialized and used.
1708
1709 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 46
1710
1711 A pointer to the QPlainTextEdit is stored as an internal property
1712 of the script function itself, so that it can be retrieved when
1713 the function is called.
1714
1715 \section1 Using QtScript Extensions
1716
1717 The QScriptEngine::importExtension() function can be used to load plugins
1718 into a script engine. Plugins typically add some extra functionality to
1719 the engine; for example, a plugin might add full bindings for the Qt
1720 Arthur painting API, so that those classes may be used from Qt Script
1721 scripts. There are currently no script plugins shipped with Qt.
1722
1723 If you are implementing some Qt Script functionality that you want other
1724 Qt application developers to be able to use, developing an extension (e.g.
1725 by subclassing QScriptExtensionPlugin) is worth looking into.
1726
1727 \section1 Internationalization
1728
1729 Since Qt 4.5, Qt Script supports internationalization of scripts by building
1730 on the C++ internationalization functionality (see \l{Internationalization
1731 with Qt}).
1732
1733 \section2 Use qsTr() for All Literal Text
1734
1735 Wherever your script uses "quoted text" for text that will be presented to
1736 the user, ensure that it is processed by the QCoreApplication::translate()
1737 function. Essentially all that is necessary to achieve this is to use
1738 the qsTr() script function. Example:
1739
1740 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 82
1741
1742 This accounts for 99% of the user-visible strings you're likely to write.
1743
1744 The qsTr() function uses the basename of the script's filename (see
1745 QFileInfo::baseName()) as the translation context; if the filename is not
1746 unique in your project, you should use the qsTranslate() function and pass a
1747 suitable context as the first argument. Example:
1748
1749 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 83
1750
1751 If you need to have translatable text completely outside a function, there
1752 are two functions to help: QT_TR_NOOP() and QT_TRANSLATE_NOOP(). They merely
1753 mark the text for extraction by the \c lupdate utility described below. At
1754 runtime, these functions simply return the text to translate unmodified.
1755
1756 Example of QT_TR_NOOP():
1757
1758 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 84
1759
1760 Example of QT_TRANSLATE_NOOP():
1761
1762 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 85
1763
1764 \section2 Use String.prototype.arg() for Dynamic Text
1765
1766 The String.prototype.arg() function (which is modeled after QString::arg())
1767 offers a simple means for substituting arguments:
1768
1769 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 86
1770
1771 \section2 Produce Translations
1772
1773 Once you are using qsTr() and/or qsTranslate() throughout your scripts, you
1774 can start producing translations of the user-visible text in your program.
1775
1776 The \l{Qt Linguist manual} provides further information about
1777 Qt's translation tools, \e{Qt Linguist}, \c lupdate and \c
1778 lrelease.
1779
1780 Translation of Qt Script scripts is a three-step process:
1781
1782 \list 1
1783
1784 \o Run \c lupdate to extract translatable text from the script source code
1785 of the Qt application, resulting in a message file for translators (a \c
1786 .ts file). The utility recognizes qsTr(), qsTranslate() and the
1787 \c{QT_TR*_NOOP()} functions described above and produces \c .ts files
1788 (usually one per language).
1789
1790 \o Provide translations for the source texts in the \c .ts file, using
1791 \e{Qt Linguist}. Since \c .ts files are in XML format, you can also
1792 edit them by hand.
1793
1794 \o Run \c lrelease to obtain a light-weight message file (a \c .qm
1795 file) from the \c .ts file, suitable only for end use. Think of the \c
1796 .ts files as "source files", and \c .qm files as "object files". The
1797 translator edits the \c .ts files, but the users of your application
1798 only need the \c .qm files. Both kinds of files are platform and
1799 locale independent.
1800
1801 \endlist
1802
1803 Typically, you will repeat these steps for every release of your
1804 application. The \c lupdate utility does its best to reuse the
1805 translations from previous releases.
1806
1807 When running \c lupdate, you must specify the location of the script(s),
1808 and the name of the \c{.ts} file to produce. Examples:
1809
1810 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 87
1811
1812 will extract translatable text from \c myscript.qs and create the
1813 translation file \c myscript_la.qs.
1814
1815 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 88
1816
1817 will extract translatable text from all files ending with \c{.qs} in the
1818 \c scripts folder and create the translation file \c scripts_la.qs.
1819
1820 Alternatively, you can create a separate qmake project file that sets up
1821 the \c SOURCES and \c TRANSLATIONS variables appropriately; then run
1822 \c lupdate with the project file as input.
1823
1824 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 89
1825
1826 When running \c lrelease, you must specify the name of the \c{.ts} input
1827 file; or, if you are using a qmake project file to manage script
1828 translations, you specify the name of that file. \c lrelease will create
1829 \c myscript_la.qm, the binary representation of the translation.
1830
1831 \section2 Apply Translations
1832
1833 In your application, you must use QTranslator::load() to load the
1834 translation files appropriate for the user's language, and install them
1835 using QCoreApplication::installTranslator(). Finally, you must call
1836 QScriptEngine::installTranslatorFunctions() to make the script translation
1837 functions (qsTr(), qsTranslate() and \c{QT_TR*_NOOP()}) available to scripts
1838 that are subsequently evaluated by QScriptEngine::evaluate(). For scripts
1839 that are using the qsTr() function, the proper filename must be passed as
1840 second argument to QScriptEngine::evaluate().
1841
1842 \c linguist, \c lupdate and \c lrelease are installed in the \c bin
1843 subdirectory of the base directory Qt is installed into. Click Help|Manual
1844 in \e{Qt Linguist} to access the user's manual; it contains a tutorial
1845 to get you started.
1846
1847 See also the \l{Hello Script Example}.
1848
1849 \section1 ECMAScript Compatibility
1850
1851 QtScript implements all the built-in classes and functions defined
1852 in ECMA-262.
1853
1854 The Date parsing and string conversion functions are implemented using
1855 QDateTime::fromString() and QDateTime::toString(), respectively.
1856
1857 The RegExp class is a wrapper around QRegExp. The QRegExp semantics
1858 do not precisely match the semantics for regular expressions defined
1859 in ECMA-262.
1860
1861 \section1 QtScript Extensions to ECMAScript
1862
1863 \list
1864 \i \c{__proto__} \br
1865 The prototype of an object (QScriptValue::prototype())
1866 can be accessed through its \c{__proto__} property in script code.
1867 This property has the QScriptValue::Undeletable flag set.
1868 For example:
1869
1870 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 40
1871
1872 \i \c{Object.prototype.__defineGetter__} \br
1873 This function installs a
1874 getter function for a property of an object. The first argument is
1875 the property name, and the second is the function to call to get
1876 the value of that property. When the function is invoked, the
1877 \c this object will be the object whose property is accessed.
1878 For example:
1879
1880 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 41
1881
1882 \i \c{Object.prototype.__defineSetter__} \br
1883 This function installs a
1884 setter function for a property of an object. The first argument is
1885 the property name, and the second is the function to call to set
1886 the value of that property. When the function is invoked, the
1887 \c this object will be the object whose property is accessed.
1888 For example:
1889
1890 \snippet doc/src/snippets/code/doc_src_qtscript.qdoc 42
1891
1892 \i \c{Function.prototype.connect} \br
1893 This function connects
1894 a signal to a slot. Usage of this function is described in
1895 the section \l{Using Signals and Slots}.
1896
1897 \i \c{Function.prototype.disconnect} \br
1898 This function disconnects
1899 a signal from a slot. Usage of this function is described in
1900 the section \l{Using Signals and Slots}.
1901
1902 \i \c{QObject.prototype.findChild} \br
1903 This function is semantically equivalent to QObject::findChild().
1904
1905 \i \c{QObject.prototype.findChildren} \br
1906 This function is semantically equivalent to QObject::findChildren().
1907
1908 \i \c{QObject.prototype.toString} \br
1909 This function returns a default string representation of a QObject.
1910
1911 \i \c{gc} \br
1912 This function invokes the garbage collector.
1913
1914 \i \c{Error.prototype.backtrace} \br
1915 This function returns a human-readable backtrace, in the form of
1916 an array of strings.
1917
1918 \i Error objects have the following additional properties:
1919 \list
1920 \i \c{lineNumber}: The line number where the error occurred.
1921 \i \c{fileName}: The file name where the error occurred (if a file name
1922 was passed to QScriptEngine::evaluate()).
1923 \i \c{stack}: An array of objects describing the stack. Each object has
1924 the following properties:
1925 \list
1926 \i \c{functionName}: The function name, if available.
1927 \i \c{fileName}: The file name, if available.
1928 \i \c{lineNumber}: The line number, if available.
1929 \endlist
1930 \endlist
1931
1932 \endlist
1933
1934 */
Note: See TracBrowser for help on using the repository browser.