diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..7f35794 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,153 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + -rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/PyOtherSide.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PyOtherSide.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/PyOtherSide" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PyOtherSide" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..9a56141 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,242 @@ +# -*- coding: utf-8 -*- +# +# PyOtherSide documentation build configuration file, created by +# sphinx-quickstart on Wed Feb 5 22:01:34 2014. +# +# This file is execfile()d with the current directory set to its containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys, os + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ----------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = [] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'PyOtherSide' +copyright = u'2014, Thomas Perl' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '0.2.0' +# The full version, including alpha/beta/rc tags. +release = '0.2.0' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + + +# -- Options for HTML output --------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'PyOtherSidedoc' + + +# -- Options for LaTeX output -------------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', 'PyOtherSide.tex', u'PyOtherSide Documentation', + u'Thomas Perl', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output -------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'pyotherside', u'PyOtherSide Documentation', + [u'Thomas Perl'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------------ + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'PyOtherSide', u'PyOtherSide Documentation', + u'Thomas Perl', 'PyOtherSide', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' diff --git a/docs/images/image_provider_example.png b/docs/images/image_provider_example.png new file mode 100644 index 0000000..3db2c76 Binary files /dev/null and b/docs/images/image_provider_example.png differ diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..baefcc0 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,573 @@ +PyOtherSide Developer Guide +=========================== + +*PyOtherSide* is a Qt 5 QML Plugin that provides access to a Python 3 +interpreter from QML. It was designed with mobile devices in mind, where +high-framerate touch interfaces are common, and where the user usually +interfaces only with one application at a time via a touchscreen. As such, it +is important to never block the UI thread, so that the user can always continue +to use the interface, even when the backend is processing, downloading or +calculating something in the background. + +At its core, PyOtherSide is basically a simple layer that converts Qt (QML) +objects to Python objects and vice versa, with focus on asynchronous events +and continuation-passing style function calls. + +While PyOtherSide historically also worked with Python 2.x and Qt 4.x, its +focus now lies on Python 3.x and Qt 5. Python 3 has been out for several years, +and offers some nice language features and clean-ups, while Qt 5 supports most +mobile platforms well, and has an improved QML engine and a faster renderer (Qt +Scene Graph) compared to Qt 4. + + +QML API +======= + +This section describes the QML API exposed by the *PyOtherSide* QML Plugin. +The current QML API version of PyOtherSide is 1.0. When new features are +introduced, the API version will be bumped and documented here. + +Import Versions +--------------- + +**io.thp.pyotherside 1.0** (since: 0.1.0) + Initial API release. + +QML ``Python`` Element +---------------------- + +The ``Python`` element exposes a Python interpreter in a QML file. In +PyOtherSide 1.0, if multiple Python elements are instantiated, they will share +the same underlying Python interpreter, so Python module-global state will be +shared between all Python elements. + +To use the ``Python`` element in a QML file, you have to import the plugin using: + +.. code-block:: javascript + + import io.thp.pyotherside 1.0 + +Signals +``````` + +**received(var data)** + Default event handler for ``pyotherside.send()`` + if no other event handler was set. + +**error(string traceback)** + Error handler for errors from Python. + +Methods +``````` + +To configure event handlers for events from Python, you can use +the ``setHandler(event, callback)`` method: + +**setHandler(string event, callable callback)** + Set the handler for events sent with ``pyotherside.send()``. + +Importing modules is then done by optionally adding an import +path and then importing the module asynchronously: + +**addImportPath(string path)** + Add a local filesystem path to Python's ``sys.path``. + +**importModule(string name, callable callback)** + Import a Python module. + +Once modules are imported, Python function can be called on the +imported modules using: + +**call(string func, args=[], function callback(result) {})** + Call the Python function ``func`` with ``args`` asynchronously. + If ``args`` is omitted, ``func`` will be called without arguments. + If ``callback`` is a callable, it will be called with the Python + function result as single argument when the call has succeeded. + +For some of these methods, there also exist synchronous variants, but it is +highly recommended to use the asynchronous variants instead to avoid blocking +the QML UI thread: + +**var evaluate(string expr)** + Evaluate a Python expression synchronously. + +**bool importModule_sync(string name)** + Import a Python module. Returns ``true`` on success, ``false`` otherwise. + +**var call_sync(string func, var args=[])** + Call a Python function. Returns the return value of the Python function. + +Python API +========== + +PyOtherSide uses a normal Python 3.x interpreter for running your Python code. + +The ``pyotherside`` module +-------------------------- + +When a module is imported in PyOtherSide, it will have access to a special +module called ``pyotherside`` in addition to all Python Standard Library modules +and Python modules in ``sys.path``: + +.. code-block:: python + + import pyotherside + +The module can be used to send events asynchronously (even from different threads) +to the QML layer, register a callback for doing clean-ups at application exit and +integrate with other QML-specific features of PyOtherSide. + +Methods +``````` + +**pyotherside.send(event, *args)** + Send an asynchronous event with name ``event`` with optional arguments ``args`` to QML. + +**pyotherside.atexit(callback)** + Register a ``callback`` to be called when the application is closing. + +**pyotherside.set_image_provider(provider)** + Set the QML `image provider`_ (``image://python/``). + +.. _constants: + +Constants +````````` + +These constants are used in the return value of a `image provider`_ function: + +**pyotherside.format_mono** + Mono pixel format (``QImage::Format_Mono``). + +**pyotherside.format_mono_lsb** + Mono pixel format, LSB alignment (``QImage::Format_MonoLSB``). + +**pyotherside.format_rgb32** + 32-bit RGB format (``QImage::Format_RGB32``). + +**pyotherside.format_argb32** + 32-bit ARGB format (``QImage::Format_ARGB32``). + +**pyotherside.format_rgb16** + 16-bit RGB format (``QImage::Format_RGB16``). + +**pyotherside.format_rgb666** + 18bpp RGB666 format (``QImage::Format_RGB666``). + +**pyotherside.format_rgb555** + 15bpp RGB555 format (``QImage::Format_RGB555``). + +**pyotherside.format_rgb888** + 24-bit RGB format (``QImage::Format_RGB888``). + +**pyotherside.format_rgb444** + 12bpp RGB format (``QImage::Format_RGB444``). + +**pyotherside.format_data** + Encoded image file data (e.g. PNG/JPEG data). + + +Data Type Mapping +================= + +PyOtherSide will automatically convert Python data types to Qt data types +(which in turn will be converted to QML data types by the QML engine). +The following data types are supported and can be used to pass data +between Python and QML (and vice versa): + ++------------+------------+-----------------------------+ +| Python | QML | Remarks | ++============+============+=============================+ +| bool | bool | | ++------------+------------+-----------------------------+ +| int | int | | ++------------+------------+-----------------------------+ +| float | double | | ++------------+------------+-----------------------------+ +| str | string | | ++------------+------------+-----------------------------+ +| list | JS Array | | ++------------+------------+-----------------------------+ +| tuple | JS Array | JS Arrays are converted to | +| | | lists, no tuples | ++------------+------------+-----------------------------+ +| dict | JS Object | Keys must be strings | ++------------+------------+-----------------------------+ + +Trying to pass in other types than the ones listed here is undefined +behavior and will usually result in an error. + +.. _image provider: + +Image Provider +============== + +A QML Image Provider can be registered from Python to load image +data (e.g. map tiles, diagrams, graphs or generated images) in +QML ``Image`` elements without resorting to saving/loading files. + +An image provider has the following argument list and return values: + +.. code-block:: python + + def image_provider(image_id, requested_size): + ... + return bytearray(pixels), (width, height), format + +The parameters to the image provider functions are: + +**image_id** + The ID of the image URL (``image://python/``). + +**requested_size** + The source size of the QML ``Image`` as tuple: ``(width, height)``. + ``(-1, -1)`` if the source size is not set. + +The image provider must return a tuple ``(data, size, format)``: + +**data** + A ``bytearray`` object containing the pixel data for the + given size and the given format. + +**size** + A tuple ``(width, height)`` describing the size of the + pixel data in pixels. + +**format** + The pixel format of ``data`` (see `constants`_), or + ``pyotherside.format_data`` if ``data`` contains an + encoded (PNG/JPEG) image instead of raw pixel data. + +In order to register the image provider with PyOtherSide for use +as provider for ``image://python/`` URLs, the image provider function +needs to be passed to PyOtherSide: + +.. code-block:: python + + import pyotherside + + def image_provider(image_id, requested_size): + ... + + pyotherside.set_image_provider(image_provider) + +Because Python modules are usually imported asynchronously, the image +provider will only be registered once the module registering the image +provider is successfully imported. You have to make sure that setting +the ``source`` property on a QML ``Image`` element only happens *after* +the image provider has been set (e.g. by setting the ``source`` property +in the callback function passed to ``importModule``). + +Cookbook +======== + +This section contains code examples and best practices for combining Python and +QML. + +Importing modules and calling functions asynchronously +------------------------------------------------------ + +In this example, we import the Python Standard Library module ``os`` +and - when the module is imported - call the ``os.getcwd()`` function on it. +The result of the ``os.getcwd()`` function is then printed to the console +and ``os.chdir()`` is called with a single argument (``'/'``) - again, after +the ``os.chdir()`` function has returned, a message will be printed. + +In this example, importing modules and calling functions are both done in +an asynchronous way - the QML/GUI thread will not block while these functions +execute. In fact, the ``Component.onCompleted`` code block will probably +finish before the ``os`` module has been imported in Python. + +.. code-block:: javascript + + Python { + Component.onCompleted: { + importModule('os', function() { + call('os.getcwd', [], function (result) { + console.log('Working directory: ' + result); + call('os.chdir', ['/'], function (result) { + console.log('Working directory changed.'); + });); + }); + }); + } + } + +While this `continuation-passing style`_ might look a like a little pyramid +due all the nesting and indentation at first, it makes sure your application's +UI is always responsive. The user will be able to interact with the GUI (e.g. +scroll and move around in the UI) while the Python code can process requests. + +.. _Continuation-passing style: https://en.wikipedia.org/wiki/Continuation-passing_style + +Evaluating Python expressions in QML +```````````````````````````````````` + +The ``evaluate()`` method on the ``Python`` object can be used to evaluate a +simple Python expression and return its result as JavaScript object: + +.. code-block:: javascript + + Python { + Component.onCompleted: { + console.log('Squares: ' + evaluate('[x for x in range(10)]')); + } + } + +Evaluating expressions is done synchronously, so make sure you only use it for +expressions that are not long-running calculations / operations. + + +Error handling in QML +--------------------- + +If an error happens in Python while calling functions, the traceback of the +error (or an error message in case the error happens in the PyOtherSide layer) +will be sent with the ``error`` signal of the ``Python`` element. During early +development, it's probably enough to just log the error to the console: + +.. code-block:: javascript + + Python { + // ... + + onError: console.log('Error: ' + traceback) + } + +Once your application grows, it might make sense to maybe show the error to the +user in a dialog box, message or notification in addition to or instead of using +``console.log()`` to print the error. + + +Handing asynchronous events from Python in QML +---------------------------------------------- + +Your Python code can send asynchronous events with optional data to the QML +layer using the ``pyotherside.send()`` function. You can call this function from +functions called from QML, but also from anywhere else - including threads that +you created in Python. The first parameter is mandatory, and must be a string +that identifies the event. Additional parameters are optional and can be of any +data type that PyOtherSide supports: + +.. code-block:: python + + import pyotherside + + pyotherside.send('new-entries', 100, 123) + +If you do not add a special handler on the ``Python`` object, such events would +be handled by the ``onReceived`` signal in QML - its ``data`` parameter contains +the event name and all arguments in a list: + +.. code-block:: javascript + + Python { + // .. + + onReceived: console.log('Event: ' + data) + } + +Usually, you want to install a handler for such events. If you have e.g. the +``'new-entries'`` event like shown above (with two numeric parameters that we +will call ``first`` and ``last`` for this example), you might want to define a +simple handler function that will process this event: + +.. code-block:: javascript + + Python { + // .. + + Component.onCompleted: { + setHandler('new-entries', function (first, last) { + console.log('New entries from ' + first + ' to ' + last); + }); + } + } + +Once a handler for a given event is defined, the ``onReceived`` signal will not +be emitted anymore. If you need to unset a handler for a given event, you can +use ``setHandler('event', undefined)`` to do so. + +In some cases, it might be useful to not install a handler function directly, but +turn the ``pyotherside.send()`` call into a new signal on the ``Python`` object. +As there is no easy way for PyOtherSide to determine the names of the arguments +of the event, you have to define and hook up these signals manually. The upside +of having to define the signals this way is that all signals will be nicely +documented in your QML file for future reference: + +.. code-block:: javascript + + Python { + signal updated() + signal newEntries(int first, int last) + signal entryRenamed(int index, string name) + + Component.onCompleted: { + setHandler('updated', updated); + setHandler('new-entries', newEntries); + setHandler('entry-renamed', entryRenamed); + } + } + +With this setup, you can now emit these signals from the ``Python`` object by +using ``pyotherside.send()`` in your Python code: + +.. code-block:: python + + pyotherside.send('updated') + pyotherside.send('new-entries', 20, 30) + pyotherside.send('entry-renamed', 11, 'Hello World') + + +Loading ``ListModel`` data from Python +-------------------------------------- + +Most of the time a PyOtherSide QML application will display some data stored +somewhere and retrieved or generated with Python. The easiest way to do this is +to return a list-of-dicts in your Python function: + +**listmodel.py** + +.. code-block:: python + + def get_data(): + return [ + {'name': 'Alpha', 'team': 'red'}, + {'name': 'Beta', 'team': 'blue'}, + {'name': 'Gamma', 'team': 'green'}, + {'name': 'Delta', 'team': 'yellow'}, + {'name': 'Epsilon', 'team': 'orange'}, + ] + +Of course, the function could do other things (such as doing web requests, querying +databases, etc..) - as long as it returns a list-olf-dicts, it will be fine (if you +are using a generator that yields dicts, just wrap the generator with ``list()``). +Using this function from QML is straightforward: + +**listmodel.qml** + +.. code-block:: javascript + + import QtQuick 2.0 + import io.thp.pyotherside 1.0 + + Rectangle { + color: 'black' + width: 400 + height: 400 + + ListView { + anchors.fill: parent + + model: ListModel { + id: listModel + } + + delegate: Text { + // Both "name" and "team" are taken from the model + text: name + color: team + } + } + + Python { + id: py + + Component.onCompleted: { + // Add the directory of this .qml file to the search path + addImportPath(Qt.resolvedUrl('.').substr('file://'.length)); + + // Import the main module and load the data + importModule('listmodel', function () { + py.call('listmodel.get_data', [], function(result) { + // Load the received data into the list model + for (var i=0; i