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