Debian Codegraph @

docs/index.rst

raw
1 PyOtherSide Developer Guide
2 ===========================
3
4 *PyOtherSide* is a QML Plugin for Qt 5 and Qt 6 that provides access to a Python 3
5 interpreter from QML. It was designed with mobile devices in mind, where
6 high-framerate touch interfaces are common, and where the user usually
7 interfaces only with one application at a time via a touchscreen. As such, it
8 is important to never block the UI thread, so that the user can always continue
9 to use the interface, even when the backend is processing, downloading or
10 calculating something in the background.
11
12 At its core, PyOtherSide is basically a simple layer that converts Qt (QML)
13 objects to Python objects and vice versa, with focus on asynchronous events
14 and continuation-passing style function calls.
15
16
17 Qt 6 Support
18 ============
19
20 .. versionadded:: 1.6.0
21
22 PyOtherSide now supports Qt 6 while retaining source compatibility with Qt 5.
23
24 The following restrictions currently apply when using Qt 6:
25
26 * ``PyGLArea`` is currently broken with Qt 6, use ``PyFBO`` instead.
27
28
29 QML API
30 =======
31
32 This section describes the QML API exposed by the *PyOtherSide* QML Plugin.
33
34 Import Versions
35 ---------------
36
37 The current QML API version of PyOtherSide is 1.5. When new features are
38 introduced, or behavior is changed, the API version will be bumped and
39 documented here.
40
41 io.thp.pyotherside 1.0
42 ``````````````````````
43
44 * Initial API release.
45
46 io.thp.pyotherside 1.2
47 ``````````````````````
48
49 * :func:`importModule` now behaves like the ``import`` statement in Python
50 for names with dots. This means that ``importModule('x.y.z', ...)`` now
51 works like ``import x.y.z`` in Python.
52
53 * If a JavaScript exception occurs in the callback passed to
54 :func:`importModule` or :func:`call`, the signal :func:`error` is emitted
55 with the exception information (filename, line, message) as ``traceback``.
56
57 io.thp.pyotherside 1.3
58 ``````````````````````
59
60 * :func:`addImportPath` now also accepts ``qrc:/`` URLs. This is useful if
61 your Python files are embedded as Qt Resources, relative to your QML files
62 (use :func:`Qt.resolvedUrl` from the QML file).
63
64 io.thp.pyotherside 1.4
65 ``````````````````````
66
67 * Added :func:`getattr`
68
69 * :func:`call` and :func:`call_sync` now accept a Python callable object
70 for the first parameter (previously, only strings were supported)
71
72 * If :func:`error` doesn't have a handler defined, error messages will be
73 printed to the console as warnings
74
75 io.thp.pyotherside 1.5
76 ``````````````````````
77
78 * Added ``PyGLArea`` and ``PyFBO`` for OpenGL rendering, see
79 `OpenGL rendering in Python`_
80
81 * Added :func:`importNames` and :func:`importNames_sync` to mirror
82 Python's ``from foo import bar, baz`` import mechanism
83
84
85
86 QML ``Python`` Element
87 ----------------------
88
89 The ``Python`` element exposes a Python interpreter in a QML file. In
90 PyOtherSide 1.0, if multiple Python elements are instantiated, they will share
91 the same underlying Python interpreter, so Python module-global state will be
92 shared between all Python elements.
93
94 To use the ``Python`` element in a QML file, you have to import the plugin using:
95
96 .. code-block:: javascript
97
98 import io.thp.pyotherside 1.5
99
100 Signals
101 ```````
102
103 .. function:: received(var data)
104
105 Default event handler for :func:`pyotherside.send`
106 if no other event handler was set.
107
108 .. function:: error(string traceback)
109
110 Error handler for errors from Python.
111
112 .. versionchanged:: 1.4.0
113 If the error signal is not connected, PyOtherSide will print the
114 error as QWarning on the console (previously, error messages
115 were only shown if the signal was connected and printed there).
116 To avoid printing the error, just define a no-op handler.
117
118 Methods
119 ```````
120
121 To configure event handlers for events from Python, you can use
122 the :func:`setHandler` method:
123
124 .. function:: setHandler(string event, callable callback)
125
126 Set the handler for events sent with :func:`pyotherside.send`.
127
128 Importing modules is then done by optionally adding an import
129 path and then importing the module asynchronously:
130
131 .. function:: addImportPath(string path)
132
133 Add a path to Python's ``sys.path``.
134
135 .. versionchanged:: 1.1.0
136 :func:`addImportPath` will automatically strip a leading
137 ``file://`` from the path, so you can use :func:`Qt.resolvedUrl()`
138 without having to manually strip the leading ``file://`` in QML.
139
140 .. versionchanged:: 1.3.0
141 Starting with QML API version 1.3 (``import io.thp.pyotherside 1.3``),
142 :func:`addImportPath` now also accepts ``qrc:/`` URLs. The first time
143 a ``qrc:/`` path is added, a new import handler will be installed,
144 which will enable Python to transparently import modules from it.
145
146 .. function:: importModule(string name, function callback(success) {})
147
148 Import a Python module.
149
150 .. versionchanged:: 1.2.0
151 Previously, this function didn't work correctly for importing
152 modules with dots in their name. Starting with the API version 1.2
153 (``import io.thp.pyotherside 1.2``), this behavior is now fixed,
154 and ``importModule('x.y.z', ...)`` behaves like ``import x.y.z``.
155
156 .. versionchanged:: 1.2.0
157 If a JavaScript exception occurs in the callback, the :func:`error`
158 signal is emitted with ``traceback`` containing the exception info
159 (QML API version 1.2 and newer).
160
161 .. function:: importNames(string module, array object_names, function callback(success) {})
162
163 Import a list of names from a given modules, like Python's
164 ``from foo import bar, baz`` syntax -- the equivalent call
165 would be ``importNames('module', ['bar', 'baz'], ...);``
166
167 .. versionadded:: 1.5.0
168
169 Once modules are imported, Python function can be called on the
170 imported modules using:
171
172 .. function:: call(var func, args=[], function callback(result) {})
173
174 Call the Python function ``func`` with ``args`` asynchronously.
175 If ``args`` is omitted, ``func`` will be called without arguments.
176 If ``callback`` is a callable, it will be called with the Python
177 function result as single argument when the call has succeeded.
178
179 .. versionchanged:: 1.2.0
180 If a JavaScript exception occurs in the callback, the :func:`error`
181 signal is emitted with ``traceback`` containing the exception info
182 (QML API version 1.2 and newer).
183
184 .. versionchanged:: 1.4.0
185 ``func`` can also be a Python callable object, not just a string.
186
187 Attributes on Python objects can be accessed using :func:`getattr`:
188
189 .. function:: getattr(obj, string attr) -> var
190
191 Get the attribute ``attr`` of the Python object ``obj``.
192
193 .. versionadded:: 1.4.0
194
195 For some of these methods, there also exist synchronous variants, but it is
196 highly recommended to use the asynchronous variants instead to avoid blocking
197 the QML UI thread:
198
199 .. function:: evaluate(string expr) -> var
200
201 Evaluate a Python expression synchronously.
202
203 .. function:: importModule_sync(string name) -> bool
204
205 Import a Python module. Returns ``true`` on success, ``false`` otherwise.
206
207 .. function:: importNames_sync(string module, array names) -> bool
208
209 Import names from a Python modules. Returns ``true`` on success, ``false`` otherwise.
210
211 .. function:: call_sync(var func, var args=[]) -> var
212
213 Call a Python function. Returns the return value of the Python function.
214
215 .. versionchanged:: 1.4.0
216 ``func`` can also be a Python callable object, not just a string.
217
218 The following functions allow access to the version of the running PyOtherSide
219 plugin and Python interpreter.
220
221 .. function:: pluginVersion() -> string
222
223 Get the version of the PyOtherSide plugin that is currently used.
224
225 .. note::
226 This is not necessarily the same as the QML API version currently in use.
227 The QML API version is decided by the QML import statement, so even if
228 :func:`pluginVersion` returns 1.2.0, if the plugin has been imported as
229 ``import io.thp.pyotherside 1.0``, the API version used would be 1.0.
230
231 .. versionadded:: 1.1.0
232
233 .. function:: pythonVersion() -> string
234
235 Get the version of the Python interpreter that is currently used.
236
237 .. versionadded:: 1.1.0
238
239 .. versionchanged:: 1.5.0
240 Previously, :func:`pythonVersion` returned the compile-time version of
241 Python against which PyOtherSide was built. Starting with version 1.5.0,
242 the run-time version of Python is returned (e.g. PyOtherSide compiled
243 against Python 3.4.0 and running with Python 3.4.1 returned "3.4.0"
244 before, but returns "3.4.1" in PyOtherSide after and including 1.5.0).
245
246 QML ``PyGLArea`` Element
247 ------------------------
248
249 .. versionadded:: 1.5.0
250
251 The PyGLArea allows rendering arbitrary OpenGL content from Python into
252 the QML scene.
253
254 Properties
255 ``````````
256
257 .. function:: PyObject renderer
258
259 Python object that implements the IRenderer interface, see
260 `OpenGL rendering in Python`_ for details.
261
262 .. function:: bool before
263
264 ``true`` to render before (= below) the rest of the QML scene,
265 ``false`` to render after (= above) the rest of the QML scene.
266 Default: ``true``
267
268 QML ``PyFBO`` Element
269 ---------------------
270
271 .. versionadded:: 1.5.0
272
273 The PyFBO allows offscreen rendering of arbitrary OpenGL content from
274 Python into the QML scene.
275
276 Properties
277 ``````````
278
279 .. function:: PyObject renderer
280
281 Python object that implements the IRenderer interface, see
282 `OpenGL rendering in Python`_ for details
283
284 Python API
285 ==========
286
287 PyOtherSide uses a normal Python 3.x interpreter for running your Python code.
288
289 The ``pyotherside`` module
290 --------------------------
291
292 When a module is imported in PyOtherSide, it will have access to a special
293 module called :mod:`pyotherside` in addition to all Python Standard Library modules
294 and Python modules in ``sys.path``:
295
296 .. code-block:: python
297
298 import pyotherside
299
300 The module can be used to send events asynchronously (even from different threads)
301 to the QML layer, register a callback for doing clean-ups at application exit and
302 integrate with other QML-specific features of PyOtherSide.
303
304 Methods
305 ```````
306
307 .. function:: pyotherside.send(event, \*args)
308
309 Send an asynchronous event with name ``event`` with optional arguments
310 ``args`` to QML.
311
312 .. function:: pyotherside.atexit(callback)
313
314 Register a ``callback`` to be called when the application is closing.
315
316 .. function:: pyotherside.set_image_provider(provider)
317
318 Set the QML `image provider`_ (``image://python/``).
319
320 .. versionadded:: 1.1.0
321
322 .. function:: pyotherside.qrc_is_file(filename)
323
324 Check if ``filename`` is an existing file in the `Qt Resource System`_.
325
326 :returns: ``True`` if ``filename`` is a file, ``False`` otherwise.
327
328 .. versionadded:: 1.3.0
329
330 .. function:: pyotherside.qrc_is_dir(dirname)
331
332 Check if ``dirname`` is an existing directory in the `Qt Resource System`_.
333
334 :returns: ``True`` if ``dirname`` is a directory, ``False`` otherwise.
335
336 .. versionadded:: 1.3.0
337
338 .. function:: pyotherside.qrc_get_file_contents(filename)
339
340 Get the file contents of a file in the `Qt Resource System`_.
341
342 :raise ValueError: If ``filename`` does not denote a valid file.
343 :returns: The file contents as Python ``bytearray`` object.
344
345 .. versionadded:: 1.3.0
346
347 .. function:: pyotherside.qrc_list_dir(dirname)
348
349 Get the entry list of a directory in the `Qt Resource System`_.
350
351 :raise ValueError: If ``dirname`` does not denote a valid directory.
352 :returns: The directory entries as list of strings.
353
354 .. versionadded:: 1.3.0
355
356 .. _Qt Resource System: http://qt-project.org/doc/qt-5/resources.html
357
358 .. _constants:
359
360 Constants
361 `````````
362
363 .. versionadded:: 1.1.0
364
365 These constants are used in the return value of a `image provider`_ function:
366
367 **pyotherside.format_mono**
368 Mono pixel format (``QImage::Format_Mono``).
369
370 **pyotherside.format_mono_lsb**
371 Mono pixel format, LSB alignment (``QImage::Format_MonoLSB``).
372
373 **pyotherside.format_rgb32**
374 32-bit RGB format (``QImage::Format_RGB32``).
375
376 **pyotherside.format_argb32**
377 32-bit ARGB format (``QImage::Format_ARGB32``).
378
379 **pyotherside.format_rgb16**
380 16-bit RGB format (``QImage::Format_RGB16``).
381
382 **pyotherside.format_rgb666**
383 18bpp RGB666 format (``QImage::Format_RGB666``).
384
385 **pyotherside.format_rgb555**
386 15bpp RGB555 format (``QImage::Format_RGB555``).
387
388 **pyotherside.format_rgb888**
389 24-bit RGB format (``QImage::Format_RGB888``).
390
391 **pyotherside.format_rgb444**
392 12bpp RGB format (``QImage::Format_RGB444``).
393
394 **pyotherside.format_data**
395 Encoded image file data (e.g. PNG/JPEG data).
396
397 .. versionadded:: 1.3.0
398
399 The following constants have been added in PyOtherSide 1.3:
400
401 **pyotherside.version**
402 Version of PyOtherSide as string.
403
404 .. versionadded:: 1.5.0
405
406 The following constants have been added in PyOtherSide 1.5:
407
408 **pyotherside.format_svg_data**
409 SVG image XML data
410
411
412 Data Type Mapping
413 =================
414
415 PyOtherSide will automatically convert Python data types to Qt data types
416 (which in turn will be converted to QML data types by the QML engine).
417 The following data types are supported and can be used to pass data
418 between Python and QML (and vice versa):
419
420 +--------------------+----------------+-----------------------------+
421 | Python | QML | Remarks |
422 +====================+================+=============================+
423 | bool | bool | |
424 +--------------------+----------------+-----------------------------+
425 | int | int | |
426 +--------------------+----------------+-----------------------------+
427 | float | double | |
428 +--------------------+----------------+-----------------------------+
429 | str | string | |
430 +--------------------+----------------+-----------------------------+
431 | list | JS Array | JS Arrays are always |
432 | | | converted to Python lists. |
433 +--------------------+----------------+-----------------------------+
434 | tuple | JS Array | |
435 +--------------------+----------------+-----------------------------+
436 | dict | JS Object | Keys must be strings |
437 +--------------------+----------------+-----------------------------+
438 | datetime.date | QML date | since PyOtherSide 1.2.0 |
439 +--------------------+----------------+-----------------------------+
440 | datetime.time | QML time | since PyOtherSide 1.2.0 |
441 +--------------------+----------------+-----------------------------+
442 | datetime.datetime | JS Date | since PyOtherSide 1.2.0 |
443 +--------------------+----------------+-----------------------------+
444 | set | JS Array | since PyOtherSide 1.3.0 |
445 +--------------------+----------------+-----------------------------+
446 | iterable | JS Array | since PyOtherSide 1.3.0 |
447 +--------------------+----------------+-----------------------------+
448 | object | (opaque) | since PyOtherSide 1.4.0 |
449 +--------------------+----------------+-----------------------------+
450 | pyotherside.QObject| QObject | since PyOtherSide 1.4.0 |
451 +--------------------+----------------+-----------------------------+
452 | bytes | JS ArrayBuffer | since PyOtherSide 1.5.6; |
453 | | | requires Qt 5.8; the C++ |
454 | | | data type is QByteArray |
455 +--------------------+----------------+-----------------------------+
456
457 Trying to pass in other types than the ones listed here is undefined
458 behavior and will usually result in an error.
459
460 .. _image provider:
461
462 Image Provider
463 ==============
464
465 .. versionadded:: 1.1.0
466
467 A QML Image Provider can be registered from Python to load image
468 data (e.g. map tiles, diagrams, graphs or generated images) in
469 QML ``Image`` elements without resorting to saving/loading files.
470
471 An image provider has the following argument list and return values:
472
473 .. code-block:: python
474
475 def image_provider(image_id, requested_size):
476 ...
477 return bytearray(pixels), (width, height), format
478
479 The parameters to the image provider functions are:
480
481 **image_id**
482 The ID of the image URL (``image://python/<image_id>``).
483
484 **requested_size**
485 The source size of the QML ``Image`` as tuple: ``(width, height)``.
486 ``(-1, -1)`` if the source size is not set.
487
488 The image provider must return a tuple ``(data, size, format)``:
489
490 **data**
491 A ``bytearray`` object containing the pixel data for the
492 given size and the given format.
493
494 **size**
495 A tuple ``(width, height)`` describing the size of the
496 pixel data in pixels.
497
498 **format**
499 The pixel format of ``data`` (see `constants`_),
500 ``pyotherside.format_data`` if ``data`` contains an
501 encoded (PNG/JPEG) image instead of raw pixel data
502 or ``pyotherside.format_svg_data`` if ``data`` contains
503 SVG image XML data.
504
505 In order to register the image provider with PyOtherSide for use
506 as provider for ``image://python/`` URLs, the image provider function
507 needs to be passed to PyOtherSide:
508
509 .. code-block:: python
510
511 import pyotherside
512
513 def image_provider(image_id, requested_size):
514 ...
515
516 pyotherside.set_image_provider(image_provider)
517
518 Because Python modules are usually imported asynchronously, the image
519 provider will only be registered once the module registering the image
520 provider is successfully imported. You have to make sure that setting
521 the ``source`` property on a QML ``Image`` element only happens *after*
522 the image provider has been set (e.g. by setting the ``source`` property
523 in the callback function passed to :func:`importModule`).
524
525 .. _qt resource access:
526
527 Qt Resource Access
528 ==================
529
530 .. versionadded:: 1.3.0
531
532 If you are using PyOtherSide in combination with an application binary compiled
533 from C++ code with Qt Resources (see `Qt Resource System`_), you can inspect
534 and access the resources from Python. This example demonstrates the API by
535 walking the whole resource tree, printing out directory names and file sizes:
536
537 .. code-block:: python
538
539 import pyotherside
540 import os.path
541
542 def walk(root):
543 for entry in pyotherside.qrc_list_dir(root):
544 name = os.path.join(root, entry)
545 if pyotherside.qrc_is_dir(name):
546 print('Directory:', name)
547 walk(name)
548 else:
549 data = pyotherside.qrc_get_file_contents(name)
550 print('File:', name, 'has', len(data), 'bytes')
551
552 walk('/')
553
554
555 Importing Python modules from Qt Resources also works starting with QML API 1.3
556 using :func:`Qt.resolvedUrl` from within a QML file in Qt Resources. As an
557 alternative, ``addImportPath('qrc:/')`` will add the root directory of the Qt
558 Resources to Python's module search path.
559
560 .. _qobjects in python:
561
562 Accessing QObjects from Python
563 ==============================
564
565 .. versionadded:: 1.4.0
566
567 Since version 1.4, PyOtherSide allows passing QObjects from QML to Python, and
568 accessing (setting / getting) properties and calling slots and dynamic methods.
569 References to QObjects passed to Python can be passed back to QML transparently:
570
571 .. code-block:: python
572
573 # Assume func will be called with a QObject as sole argument
574 def func(qobject):
575 # Getting properties
576 print(qobject.x)
577
578 # Setting properties
579 qobject.x = 123
580
581 # Calling slots and dynamic functions
582 print(qobject.someFunction(123, 'b'))
583
584 # Returning a QObject reference to the caller
585 return qobject
586
587 It is possible to store a reference (bound method) to a method of a QObject.
588 Such references cannot be passed to QML, and can only be used in Python for the
589 lifetime of the QObject. If you need to pass such a bound method to QML, you
590 can wrap it into a Python object (or even just a lambda) and pass that instead:
591
592 .. code-block:: python
593
594 def func(qobject):
595 # Can store a reference to a bound method
596 bound_method = qobject.someFunction
597
598 # Calling the bound method
599 bound_method(123, 'b')
600
601 # If you need to return the bound method, you must wrap it
602 # in a lambda (or any other Python object), the bound method
603 # cannot be returned as-is for now
604 return lambda a, b: bound_method(a, b)
605
606 It's not possible to instantiate new QObjects from within Python, and it's
607 not possible to subclass QObject from within Python. Also, be aware that a
608 reference to a QObject in Python will become invalid when the QObject is
609 deleted (there's no way for PyOtherSide to prevent referenced QObjects from
610 being deleted, but PyOtherSide tries hard to detect the deletion of objects
611 and give meaningful error messages in case the reference is accessed).
612
613 Calling signals of QML objects
614 ------------------------------
615
616 .. versionadded:: 1.5.4
617
618 Calling (emitting) signals of QML objects is supported since PyOtherSide 1.5.4.
619 However, as signals do not have a return value as such, the return value is
620 either just `true` or `false`, depending on whether the call worked or not.
621
622 OpenGL rendering in Python
623 ==========================
624
625 .. versionadded:: 1.5.0
626
627 You can render directly to a QML application's OpenGL context in your Python
628 code (i.e. via PyOpenGL or vispy.gloo) by using a ``PyGLArea`` or ``PyFBO`` item.
629
630 The ``IRenderer`` interface that needs to be implemented in Python and set
631 as the ``renderer`` property of ``PyGLArea`` or ``PyFBO`` needs to provide
632 the following functions:
633
634 .. function:: IRenderer.init()
635
636 Initialize OpenGL resources required for rendering.
637 This method is optional.
638
639 .. function:: IRenderer.reshape(x, y, width, height)
640
641 Called when the geometry has changed.
642
643 ``(x, y)`` is the position of the bottom left corner of the area, in
644 window coordinates, e.g. (0, 0) is the bottom left corner of the window.
645
646 .. function:: IRenderer.render()
647
648 Render to the OpenGL context.
649
650 It is the renderer's responsibility to unbind any used resources to leave
651 the context in a clean state.
652
653 .. function:: IRenderer.cleanup()
654
655 Free any resources allocated by :func:`IRenderer.init`.
656 This method is optional.
657
658
659 See `Rendering with PyOpenGL`_ for an example implementation.
660
661 Note that you might to use a recent version of PyOpenGL (>= 3.1.0) for some of
662 the examples to work, earlier versions had problems. If your distribution does
663 not provide new versions, you can install the most recent version of PyOpenGL
664 to your ``$HOME`` using:
665
666 .. code-block:: shell
667
668 pip3 install --user --upgrade PyOpenGL PyOpenGL_accelerate
669
670 Cookbook
671 ========
672
673 This section contains code examples and best practices for combining Python and
674 QML.
675
676 Importing modules and calling functions asynchronously
677 ------------------------------------------------------
678
679 In this example, we import the Python Standard Library module ``os``
680 and - when the module is imported - call the :func:`os.getcwd` function on it.
681 The result of the :func:`os.getcwd` function is then printed to the console
682 and :func:`os.chdir` is called with a single argument (``'/'``) - again, after
683 the :func:`os.chdir` function has returned, a message will be printed.
684
685 In this example, importing modules and calling functions are both done in
686 an asynchronous way - the QML/GUI thread will not block while these functions
687 execute. In fact, the ``Component.onCompleted`` code block will probably
688 finish before the :mod:`os` module has been imported in Python.
689
690 .. code-block:: javascript
691
692 Python {
693 Component.onCompleted: {
694 importModule('os', function() {
695 call('os.getcwd', [], function (result) {
696 console.log('Working directory: ' + result);
697 call('os.chdir', ['/'], function (result) {
698 console.log('Working directory changed.');
699 }););
700 });
701 });
702 }
703 }
704
705 While this `continuation-passing style`_ might look a like a little pyramid
706 due all the nesting and indentation at first, it makes sure your application's
707 UI is always responsive. The user will be able to interact with the GUI (e.g.
708 scroll and move around in the UI) while the Python code can process requests.
709
710 .. _Continuation-passing style: https://en.wikipedia.org/wiki/Continuation-passing_style
711
712 To avoid what's called `callback hell`_ in JavaScript, you can pull out the
713 anonymous functions you give as callbacks, give them names and pass them to
714 the API functions via name, e.g. the above example would turn into a shallow
715 structure (of course, in this example, splitting everything out does not make
716 too much sense, as the functions are very simple to begin with, but it's here
717 to demonstrate how splitting a callback hell pyramid basically works):
718
719 .. _callback hell: http://callbackhell.com/
720
721 .. code-block:: javascript
722
723 Python {
724 Component.onCompleted: {
725 function changedCwd(result) {
726 console.log('Working directory changed.');
727 }
728
729 function gotCwd(result) {
730 console.log('Working directory: ' + result);
731 call('os.chdir', ['/'], changedCwd);
732 }
733
734 function withOs() {
735 call('os.getcwd', [], gotCwd);
736 }
737
738 importModule('os', withOs);
739 }
740 }
741
742 Evaluating Python expressions in QML
743 ````````````````````````````````````
744
745 The :func:`evaluate` method on the ``Python`` object can be used to evaluate a
746 simple Python expression and return its result as JavaScript object:
747
748 .. code-block:: javascript
749
750 Python {
751 Component.onCompleted: {
752 console.log('Squares: ' + evaluate('[x for x in range(10)]'));
753 }
754 }
755
756 Evaluating expressions is done synchronously, so make sure you only use it for
757 expressions that are not long-running calculations / operations.
758
759
760 Error handling in QML
761 ---------------------
762
763 If an error happens in Python while calling functions, the traceback of the
764 error (or an error message in case the error happens in the PyOtherSide layer)
765 will be sent with the :func:`error` signal of the ``Python`` element. During early
766 development, it's probably enough to just log the error to the console:
767
768 .. code-block:: javascript
769
770 Python {
771 // ...
772
773 onError: console.log('Error: ' + traceback)
774 }
775
776 Once your application grows, it might make sense to maybe show the error to the
777 user in a dialog box, message or notification in addition to or instead of using
778 :func:`console.log()` to print the error.
779
780
781 Handling asynchronous events from Python in QML
782 -----------------------------------------------
783
784 Your Python code can send asynchronous events with optional data to the QML
785 layer using the :func:`pyotherside.send` function. You can call this function from
786 functions called from QML, but also from anywhere else - including threads that
787 you created in Python. The first parameter is mandatory, and must be a string
788 that identifies the event. Additional parameters are optional and can be of any
789 data type that PyOtherSide supports:
790
791 .. code-block:: python
792
793 import pyotherside
794
795 pyotherside.send('new-entries', 100, 123)
796
797 If you do not add a special handler on the ``Python`` object, such events would
798 be handled by the :func:`received` signal handler in QML - its ``data`` parameter
799 contains the event name and all arguments in a list:
800
801 .. code-block:: javascript
802
803 Python {
804 // ..
805
806 onReceived: console.log('Event: ' + data)
807 }
808
809 Usually, you want to install a handler for such events. If you have e.g. the
810 ``'new-entries'`` event like shown above (with two numeric parameters that we
811 will call ``first`` and ``last`` for this example), you might want to define a
812 simple handler function that will process this event:
813
814 .. code-block:: javascript
815
816 Python {
817 // ..
818
819 Component.onCompleted: {
820 setHandler('new-entries', function (first, last) {
821 console.log('New entries from ' + first + ' to ' + last);
822 });
823 }
824 }
825
826 Once a handler for a given event is defined, the :func:`received` signal will not
827 be emitted anymore. If you need to unset a handler for a given event, you can
828 use ``setHandler('event', undefined)`` to do so.
829
830 In some cases, it might be useful to not install a handler function directly, but
831 turn the :func:`pyotherside.send` call into a new signal on the ``Python`` object.
832 As there is no easy way for PyOtherSide to determine the names of the arguments
833 of the event, you have to define and hook up these signals manually. The upside
834 of having to define the signals this way is that all signals will be nicely
835 documented in your QML file for future reference:
836
837 .. code-block:: javascript
838
839 Python {
840 signal updated()
841 signal newEntries(int first, int last)
842 signal entryRenamed(int index, string name)
843
844 Component.onCompleted: {
845 setHandler('updated', updated);
846 setHandler('new-entries', newEntries);
847 setHandler('entry-renamed', entryRenamed);
848 }
849 }
850
851 With this setup, you can now emit these signals from the ``Python`` object by
852 using :func:`pyotherside.send` in your Python code:
853
854 .. code-block:: python
855
856 pyotherside.send('updated')
857 pyotherside.send('new-entries', 20, 30)
858 pyotherside.send('entry-renamed', 11, 'Hello World')
859
860
861 Loading ``ListModel`` data from Python
862 --------------------------------------
863
864 Most of the time a PyOtherSide QML application will display some data stored
865 somewhere and retrieved or generated with Python. The easiest way to do this is
866 to return a list-of-dicts in your Python function:
867
868 **listmodel.py**
869
870 .. code-block:: python
871
872 def get_data():
873 return [
874 {'name': 'Alpha', 'team': 'red'},
875 {'name': 'Beta', 'team': 'blue'},
876 {'name': 'Gamma', 'team': 'green'},
877 {'name': 'Delta', 'team': 'yellow'},
878 {'name': 'Epsilon', 'team': 'orange'},
879 ]
880
881 Of course, the function could do other things (such as doing web requests, querying
882 databases, etc..) - as long as it returns a list-of-dicts, it will be fine (if you
883 are using a generator that yields dicts, just wrap the generator with :func:`list`).
884 Using this function from QML is straightforward:
885
886 **listmodel.qml**
887
888 .. code-block:: javascript
889
890 import QtQuick 2.0
891 import io.thp.pyotherside 1.5
892
893 Rectangle {
894 color: 'black'
895 width: 400
896 height: 400
897
898 ListView {
899 anchors.fill: parent
900
901 model: ListModel {
902 id: listModel
903 }
904
905 delegate: Text {
906 // Both "name" and "team" are taken from the model
907 text: name
908 color: team
909 }
910 }
911
912 Python {
913 id: py
914
915 Component.onCompleted: {
916 // Add the directory of this .qml file to the search path
917 addImportPath(Qt.resolvedUrl('.'));
918
919 // Import the main module and load the data
920 importModule('listmodel', function () {
921 py.call('listmodel.get_data', [], function(result) {
922 // Load the received data into the list model
923 for (var i=0; i<result.length; i++) {
924 listModel.append(result[i]);
925 }
926 });
927 });
928 }
929 }
930 }
931
932 Instead of passing a list-of-dicts, it is of course also possible to send
933 new list items via :func:`pyotherside.send`, one item at a time, and append
934 them to the list model that way.
935
936 Rendering RGBA image data in Python
937 -----------------------------------
938
939 .. versionadded:: 1.1.0
940
941 .. image:: images/image_provider_example.png
942
943 This example uses the `image provider`_ feature of PyOtherSide to
944 render RGB image data in Python and display the rendered data in
945 QML using a normal QtQuick 2.0 ``Image`` element:
946
947 **imageprovider.py**
948
949 .. code-block:: python
950
951 import pyotherside
952 import math
953
954 def render(image_id, requested_size):
955 print('image_id: "{image_id}", size: {requested_size}'.format(**locals()))
956
957 # width and height will be -1 if not set in QML
958 if requested_size == (-1, -1):
959 requested_size = (300, 300)
960
961 width, height = requested_size
962
963 # center for circle
964 cx, cy = width/2, 10
965
966 pixels = []
967 for y in range(height):
968 for x in range(width):
969 pixels.extend(reversed([
970 255, # alpha
971 int(10 + 10 * ((x - y * 0.5) % 20)), # red
972 20 + 10 * (y % 20), # green
973 int(255 * abs(math.sin(0.3*math.sqrt((cx-x)**2 + (cy-y)**2)))) # blue
974 ]))
975 return bytearray(pixels), (width, height), pyotherside.format_argb32
976
977 pyotherside.set_image_provider(render)
978
979 This module can now be imported in QML and used as ``source`` in the QML
980 ``Image`` element:
981
982 **imageprovider.qml**
983
984 .. code-block:: javascript
985
986 import QtQuick 2.0
987 import io.thp.pyotherside 1.5
988
989 Image {
990 id: image
991 width: 300
992 height: 300
993
994 Python {
995 Component.onCompleted: {
996 // Add the directory of this .qml file to the search path
997 addImportPath(Qt.resolvedUrl('.'));
998
999 importModule('imageprovider', function () {
1000 image.source = 'image://python/image-id-passed-from-qml';
1001 });
1002 }
1003
1004 onError: console.log('Python error: ' + traceback)
1005 }
1006 }
1007
1008 Rendering with PyOpenGL
1009 -----------------------
1010
1011 .. versionadded:: 1.5.0
1012
1013 .. image:: images/pyfbo_example.png
1014
1015 The example below shows how to do raw OpenGL rendering in PyOpenGL using
1016 ``PyGLArea``. It has been adapted from the tutorial in the Qt documentation at
1017 http://qt-project.org/doc/qt-5/qtquick-scenegraph-openglunderqml-example.html.
1018
1019 **renderer.py**
1020
1021 .. code-block:: python
1022
1023 import numpy
1024
1025 from OpenGL.GL import *
1026 from OpenGL.GL.shaders import compileShader, compileProgram
1027
1028 VERTEX_SHADER = """#version 130
1029 attribute highp vec4 vertices;
1030 varying highp vec2 coords;
1031
1032 void main() {
1033 gl_Position = vertices;
1034 coords = vertices.xy;
1035 }
1036 """
1037
1038 FRAGMENT_SHADER = """#version 130
1039 uniform lowp float t;
1040 varying highp vec2 coords;
1041 void main() {
1042 lowp float i = 1. - (pow(abs(coords.x), 4.) + pow(abs(coords.y), 4.));
1043 i = smoothstep(t - 0.8, t + 0.8, i);
1044 i = floor(i * 20.) / 20.;
1045 gl_FragColor = vec4(coords * .5 + .5, i, i);
1046 }
1047 """
1048
1049 class Renderer(object):
1050
1051 def __init__(self):
1052 self.t = 0.0
1053 self.values = numpy.array([
1054 -1.0, -1.0,
1055 1.0, -1.0,
1056 -1.0, 1.0,
1057 1.0, 1.0
1058 ], dtype=numpy.float32)
1059
1060 def set_t(self, t):
1061 self.t = t
1062
1063 def init(self):
1064 self.vertexbuffer = glGenBuffers(1)
1065 vertex_shader = compileShader(VERTEX_SHADER, GL_VERTEX_SHADER)
1066 fragment_shader = compileShader(FRAGMENT_SHADER, GL_FRAGMENT_SHADER)
1067 self.program = compileProgram(vertex_shader, fragment_shader)
1068 self.vertices_attr = glGetAttribLocation(self.program, b'vertices')
1069 self.t_attr = glGetUniformLocation(self.program, b't')
1070
1071 def reshape(self, x, y, width, height):
1072 glViewport(x, y, width, height)
1073
1074 def render(self):
1075 glUseProgram(self.program)
1076 try:
1077 glDisable(GL_DEPTH_TEST)
1078 glClearColor(0, 0, 0, 1)
1079 glClear(GL_COLOR_BUFFER_BIT)
1080 glEnable(GL_BLEND)
1081 glBlendFunc(GL_SRC_ALPHA, GL_ONE)
1082
1083 glBindBuffer(GL_ARRAY_BUFFER, self.vertexbuffer)
1084 glEnableVertexAttribArray(self.vertices_attr)
1085 glBufferData(GL_ARRAY_BUFFER, self.values, GL_STATIC_DRAW)
1086 glVertexAttribPointer(self.vertices_attr, 2, GL_FLOAT, GL_FALSE, 0, None)
1087 glUniform1f(self.t_attr, self.t)
1088
1089 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4)
1090 finally:
1091 glDisableVertexAttribArray(0)
1092 glBindBuffer(GL_ARRAY_BUFFER, 0)
1093 glUseProgram(0)
1094
1095 def cleanup(self):
1096 glDeleteProgram(self.program)
1097 glDeleteBuffers(1, [self.vertexbuffer])
1098
1099 **pyglarea.qml**
1100
1101 .. code-block:: javascript
1102
1103 import QtQuick 2.0
1104 import io.thp.pyotherside 1.5
1105
1106 Item {
1107 width: 320
1108 height: 480
1109
1110 PyGLArea {
1111 id: glArea
1112 anchors.fill: parent
1113 property var t: 0
1114
1115 SequentialAnimation on t {
1116 NumberAnimation { to: 1; duration: 2500; easing.type: Easing.InQuad }
1117 NumberAnimation { to: 0; duration: 2500; easing.type: Easing.OutQuad }
1118 loops: Animation.Infinite
1119 running: true
1120 }
1121
1122 onTChanged: {
1123 if (renderer) {
1124 py.call(py.getattr(renderer, 'set_t'), [t], update);
1125 }
1126 }
1127 }
1128
1129 Rectangle {
1130 color: Qt.rgba(1, 1, 1, 0.7)
1131 radius: 10
1132 border.width: 1
1133 border.color: "white"
1134 anchors.fill: label
1135 anchors.margins: -10
1136 }
1137
1138 Text {
1139 id: label
1140 color: "black"
1141 wrapMode: Text.WordWrap
1142 text: "The background here is a squircle rendered with raw OpenGL using a PyGLArea. This text label and its border is rendered using QML"
1143 anchors.right: parent.right
1144 anchors.left: parent.left
1145 anchors.bottom: parent.bottom
1146 anchors.margins: 20
1147 }
1148
1149 Python {
1150 id: py
1151
1152 Component.onCompleted: {
1153 addImportPath(Qt.resolvedUrl('.'));
1154 importModule('renderer', function () {
1155 call('renderer', [], function (renderer) {
1156 glArea.renderer = renderer;
1157 });
1158 });
1159 }
1160
1161 onError: console.log(traceback);
1162 }
1163 }
1164
1165
1166 Building PyOtherSide
1167 ====================
1168
1169 The following build requirements have to be satisfied to build PyOtherSide:
1170
1171 * Qt 5.1.0 or newer (Qt 6.x also supported)
1172 * Python 3.8.0 or newer
1173
1174 If you have the required build-dependencies installed, building and installing
1175 the PyOtherSide plugin should be as simple as:
1176
1177 .. code-block:: sh
1178
1179 qmake # for Qt 6, use "qmake6"
1180 make
1181 make install
1182
1183 In case your system doesn't provide ``python3-config``, you might have to
1184 pass a suitable ``python-config`` to ``qmake`` at configure time:
1185
1186 .. code-block:: sh
1187
1188 qmake PYTHON_CONFIG=python3.8-config # For Qt 6, use "qmake6"
1189 make
1190 make install
1191
1192 Alternatively, you can edit ``python.pri`` manually and specify the compiler
1193 flags for compiling and linking against Python on your system.
1194
1195
1196 ChangeLog
1197 =========
1198
1199 Version 1.6.2 (2025-02-15)
1200 --------------------------
1201
1202 * Do not call PyEval_InitThreads(); not needed since Python 3.7 (PR#132)
1203 * Fixed PyOtherSideQtRCImporter for submodule imports (PR#134)
1204
1205 Version 1.6.1 (2024-05-18)
1206 --------------------------
1207
1208 * Dropped support for Python < 3.8 (PR#131)
1209 * Added support for Python 3.12 (PR#131)
1210 * Support for Qt 6.5 and newer (backwards-incompatible ``Q_RETURN_ARG()`` change) (fixes #128)
1211
1212 Version 1.6.0 (2022-08-05)
1213 --------------------------
1214
1215 * Support for **Qt 6** (Qt 5 is still supported for now)
1216 * Use ``PyUnicode_AsUTF8`` from Python 3.3 when converting strings; strings returned
1217 from the converter are now valid as long as the ``PyObject`` is alive (previously
1218 they were valid until the next string conversion or until converter was destroyed)
1219 * Fixed ``image_loader`` and ``imageprovider_svg_data`` examples
1220 * Removed outdated build instructions for Android and Windows
1221
1222 Version 1.5.9 (2020-01-17)
1223 --------------------------
1224
1225 * Fix compilation on Windows with VS 2017 by avoiding VLAs (by Igor Malinovskiy, PR#106)
1226 * Ensure the Python GIL is obtained in unit tests, fixes Python 3.9-related crashes (fixes #111)
1227
1228 Version 1.5.8 (2019-06-16)
1229 --------------------------
1230
1231 * Really fix Python 3.8 build compatibility (fix by Dan Church, PR#105)
1232
1233 Version 1.5.7 (2019-06-06)
1234 --------------------------
1235
1236 * Fix Python 3.8 build compatibility by adding ``--embed`` to ``python-config`` (with fallback for previous versions)
1237
1238 Version 1.5.6 (2019-06-06)
1239 --------------------------
1240
1241 * Add support for ``QByteArray``, JS ``ArrayBuffer`` and Python ``bytes`` conversion (by Igor Malinovskiy, PR#103)
1242
1243 Version 1.5.5 (2019-06-04)
1244 --------------------------
1245
1246 * Include ``dlfcn.h`` to fix build errors against musl libc (by Heiko Becker, PR#100)
1247 * Add ``--libs`` to ``python3-config`` command line (due to Python Issue 21536 changes; fixes #102)
1248
1249 Version 1.5.4 (2019-01-27)
1250 --------------------------
1251
1252 * Initialize ``sys.argv`` in Python for libraries that depend on it (issue #77)
1253 * Update ``plugins.qmltypes`` and cleanup project files (by martyone, PR#95)
1254 * Allow calling signals on QML objects from Python (issue #98)
1255
1256 Version 1.5.3 (2017-10-14)
1257 --------------------------
1258
1259 * Fix refcounting/ownership issue when using the QRC importer module (issue #84)
1260
1261 Version 1.5.2 (2017-10-14)
1262 --------------------------
1263
1264 * Fix Python-to-Qt conversion for integers > 32 bits on platforms where ``sizeof(long)`` is 4 bytes (issue #86)
1265
1266 Version 1.5.1 (2017-03-17)
1267 --------------------------
1268
1269 * Fix :func:`call_sync` when used with parameters (fix by Robie Basak; issue #49)
1270
1271 Version 1.5.0 (2016-06-14)
1272 --------------------------
1273
1274 * Support for `OpenGL rendering in Python`_ using PyOpenGL >= 3.1.0
1275 * New QML components: ``PyGLArea``, ``PyFBO``
1276 * :func:`pythonVersion` now returns the runtime Python version
1277 * Add the library to ``PYTHONPATH`` for standard library appended as .zip (except on Windows)
1278 * Call ``PyDateTime_IMPORT`` as often as necessary (Fixes #46)
1279 * Added ``pyotherside.format_svg_data`` for using SVG data in the image provider
1280 * Handle converting ``QVariantHash`` to Python ``dict`` type
1281 * Added ``.qmltypes`` file to provide metadata information for Qt Creator
1282 * New functions :func:`importNames` and :func:`importNames_sync` for from-imports
1283
1284 Version 1.4.0 (2015-02-19)
1285 --------------------------
1286
1287 * Support for passing Python objects to QML and keeping references there
1288 * Add :func:`getattr` to get an attribute from a Python object
1289 * :func:`call` and :func:`call_sync` now also accept a Python callable as
1290 first argument
1291 * Support for `Accessing QObjects from Python`_ (properties and slots)
1292 * Print error messages to the console if :func:`error` doesn't have any
1293 handlers connected
1294
1295 Version 1.3.0 (2014-07-24)
1296 --------------------------
1297
1298 * Access to the `Qt Resource System`_ from Python (see `Qt Resource Access`_).
1299 * QML API 1.3: Import from Qt Resources (:func:`addImportPath` with ``qrc:/``).
1300 * Add ``pyotherside.version`` constant to access version from Python as string.
1301 * Support for building on Windows, build instructions for Windows builds.
1302 * New data type conversions: Python ``set`` and iterable types (e.g. generator
1303 expressions and generators) are converted to JS ``Array``.
1304
1305 Version 1.2.0 (2014-02-16)
1306 --------------------------
1307
1308 * Introduced versioned QML imports for API change.
1309 * QML API 1.2: Change :func:`importModule` behavior for imports with dots.
1310 * QML API 1.2: Emit :func:`error` when JavaScript callbacks passed to
1311 :func:`importModule` and :func:`call` throw an exception.
1312 * New data type conversions: Python ``datetime.date``, ``datetime.time``
1313 and ``datetime.datetime`` are converted to QML ``date``, ``time`` and
1314 JS ``Date`` types, respectively.
1315
1316 Version 1.1.0 (2014-02-06)
1317 --------------------------
1318
1319 * Add support for Python-based image providers (see `Image Provider`_).
1320 * Fix threading crashes and aborts due to assertions.
1321 * :func:`addImportPath` will automatically strip a leading ``file://``.
1322 * Added :func:`pluginVersion` and :func:`pythonVersion` for runtime version detection.
1323
1324 Version 1.0.0 (2013-08-08)
1325 --------------------------
1326
1327 * Initial QML plugin release.
1328
1329 Version 0.0.1 (2013-05-17)
1330 --------------------------
1331
1332 * Proof-of-concept (based on a prototype from May 2011).
1333