#ifndef _PYTHONQTDOC_H1#define _PYTHONQTDOC_H23/*4*5* Copyright (C) 2006 MeVis Research GmbH All Rights Reserved.6*7* This library is free software; you can redistribute it and/or8* modify it under the terms of the GNU Lesser General Public9* License as published by the Free Software Foundation; either10* version 2.1 of the License, or (at your option) any later version.11*12* This library is distributed in the hope that it will be useful,13* but WITHOUT ANY WARRANTY; without even the implied warranty of14* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU15* Lesser General Public License for more details.16*17* Further, this software is distributed without any warranty that it is18* free of the rightful claim of any third person regarding infringement19* or the like. Any license provided herein, whether implied or20* otherwise, applies only to this software file. Patent licenses, if21* any, provided herein do not apply to combinations of this program with22* other software, or any other product whatsoever.23*24* You should have received a copy of the GNU Lesser General Public25* License along with this library; if not, write to the Free Software26* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA27*28* Contact information: MeVis Research GmbH, Universitaetsallee 29,29* 28359 Bremen, Germany or:30*31* http://www.mevis.de32*33*/3435//----------------------------------------------------------------------------------36/*!37// \file PythonQtDoc.h38// \author Florian Link39// \author Last changed by $Author: florian $40// \date 2006-1041*/42//----------------------------------------------------------------------------------4344/*!45\mainpage4647\section Introduction4849\b PythonQt is a dynamic Python (http://www.python.org) binding for Qt50(http://www.trolltech.com). It offers an easy way to embed the Python scripting51language into your Qt applications. It makes heavy use of the QMetaObject system52and thus requires Qt4.x.5354In contrast to <a href="http://www.riverbankcomputing.co.uk/pyqt/">PyQt</a> ,55PythonQt is \b not a complete Python wrapper around the complete Qt56functionality. So if you are looking for a way to write complete applications in57Python using the Qt GUI, you should use PyQt.5859If you are looking for a simple way to embed the Python language into your Qt60Application and to script parts of your application via Python, PythonQt is the61way to go!6263PythonQt is a stable library that was developed to make the Image Processing64and Visualization platform MeVisLab (http://www.mevislab.de) scriptable from65Python.6667\section Licensing6869PythonQt is distributed under the LGPL license.7071\section Download7273PythonQt is hosted on SourceForge at http://sourceforge.net/projects/pythonqt ,74you can access it via SVN or download a tarball.7576\section Features7778- Access all \b slots, \b properties, children and registered enums of any79QObject derived class from Python80- Connecting Qt Signals to Python functions (both from within Python and from81C++)82- Wrapping of C++ objects (which are not derived from QObject) via83PythonQtCPPWrapperFactory84- Extending C++ and QObject derived classes with additional slots, static85methods and constructors (see Decorators)86- StdOut/Err redirection to Qt signals instead of cout87- Interface for creating your own \c import replacement, so that Python scripts88can be e.g. signed/verified before they are executed (PythonQtImportInterface)89- Mapping of plain-old-datatypes and ALL QVariant types to and from Python90- Support for wrapping of user QVariant types which are registered via91QMetaType92- Support for Qt namespace (with all enumerators)93- All PythonQt wrapped objects support the dir() statement, so that you can see94easily which attributes a QObject, CPP object or QVariant has95- No preprocessing/wrapping tool needs to be started, PythonQt can script any96QObject without prior knowledge about it (except for the MetaObject information97from the \b moc)9899\section Non-Features100101Features that PythonQt does NOT support (and will not support):102103- you can not derive from QObjects inside of Python, this would require wrapper104generation like PyQt does105- you can only script QObject derived classes, for normal C++ classes you need106to create a PythonQtCPPWrapperFactory and adequate wrapper classes or add107decorator slots108- you can not access normal member functions of QObjects, only slots and109properties, because the \b moc does not store normal member functions in the110MetaObject system111112\section Interface113114The main interface to PythonQt is the PythonQt singleton.115PythonQt needs to be initialized via PythonQt::init() once.116Afterwards you communicate with the singleton via PythonQt::self().117PythonQt offers a default binding for the complete QWidget set, which118needs to be enabled via PythonQtGui::init().119120121\section Datatype Datatype Mapping122123The following table shows the mapping between Python and Qt objects:124<table>125<tr><th>Qt/C++</th><th>Python</th></tr>126<tr><td>bool</td><td>bool</td></tr>127<tr><td>double</td><td>float</td></tr>128<tr><td>float</td><td>float</td></tr>129<tr><td>char/uchar,int/uint,short,ushort,QChar</td><td>integer</td></tr>130<tr><td>long</td><td>integer</td></tr>131<tr><td>ulong,longlong,ulonglong</td><td>long</td></tr>132<tr><td>QString</td><td>unicode string</td></tr>133<tr><td>QByteArray</td><td>str</td></tr>134<tr><td>char*</td><td>str</td></tr>135<tr><td>QStringList</td><td>tuple of unicode strings</td></tr>136<tr><td>QVariantList</td><td>tuple of objects</td></tr>137<tr><td>QVariantMap</td><td>dict of objects</td></tr>138<tr><td>QVariant</td><td>depends on type, see below</td></tr>139<tr><td>QSize, QRect and all other standard Qt QVariants</td><td>variant140wrapper that supports complete API of the respective Qt classes</td></tr>141<tr><td>OwnRegisteredMetaType</td><td>variant wrapper, optionally with a142wrapper provided by addVariantWrapper()</td></tr>143<tr><td>EnumType</td><td>integer (all enums that are known via the moc and the144Qt namespace are supported)</td></tr> <tr><td>QObject (and derived145classes)</td><td>QObject wrapper</td></tr> <tr><td>C++ object</td><td>CPP146wrapper, either wrapped via PythonQtCPPWrapperFactory or just decorated with147decorators</td></tr> <tr><td>PyObject</td><td>PyObject</td></tr>148</table>149150PyObject is passed as simple pointer, which allows to pass/return any Python151Object directly to/from a Qt slot. QVariants are mapped recursively as given152above, e.g. a dictionary can contain lists of dictionaries of doubles. For153example a QVariant of type "String" is mapped to a python unicode string. All Qt154QVariant types are implemented, PythonQt supports the complete Qt API for these155object.156157\section QObject QObject Wrapping158159All classes derived from QObject are automatically wrapped with a python160wrapper class when they become visible to the Python interpreter. This can161happen via162- the PythonQt::addObject() method163- when a Qt \b slot returns a QObject derived object to python164- when a Qt \b signal contains a QObject and is connected to a python function165166It is important that you call PythonQt::registerClass() for any QObject derived167class that may become visible to Python, except when you add it via168PythonQt::addObject(). This will register the complete parent hierarchy of the169registered class, so that when you register e.g. a QPushButton, QWidget will be170registered as well (and all intermediate parents).171172From Python, you can talk to the returned QObjects in a natural way by calling173their slots and receiving the return values. You can also read/write all174properties of the objects as if they where normal python properties.175176In addition to this, the wrapped objects support177- className() - returns a string that represents the classname of the QObject178- help() - shows all properties, slots, enums, decorator slots and constructors179of the object, in a printable form180- connect(signal, function) - connect the signal of the given object to a181python function182- connect(signal, qobject, slot) - connect the signal of the given object to a183slot of another QObject184- disconnect(signal, function) - disconnect the signal of the given object from185a python function186- disconnect(signal, qobject, slot) - disconnect the signal of the given object187from a slot of another QObject188- children() - returns the children of the object189- setParent(QObject) - set the parent190- QObject* parent() - get the parent191192The below example shows how to connect signals in Python:193194\code195# define a signal handler function196def someFunction(flag):197print flag198199# button1 is a QPushButton that has been added to Python via addObject()200# connect the clicked signal to a python function:201button1.connect("clicked(bool)", someFunction)202203\endcode204205\section CPP CPP Wrapping206207You can create dedicated wrapper QObject for any C++ class. This is done by208deriving from PythonQtCPPWrapperFactory and adding your factory via209addWrapperFactory(). Whenever PythonQt encounters a CPP pointer (e.g. on a slot210or signal) and it does not known it as a QObject derived class, it will create a211generic CPP wrapper. So even unknown C++ objects can be passed through Python.212If the wrapper factory supports the CPP class, a QObject wrapper will be created213for each instance that enters Python. An alternative to a complete wrapper via214the wrapper factory are decorators, see \ref Decorators215216\section MetaObject Meta Object/Class access217218For each known CPP class, QObject derived class and QVariant type, PythonQt219provides a Meta class. These meta classes are visible inside of the "PythonQt"220python module.221222A Meta class supports:223224- access to all declared enum values225- constructors226- static decorator slots227- help() and className()228229From within Python, you can import the module "PythonQt" to access these meta230objects and the Qt namespace.231232\code233from PythonQt import *234235# namespace access:236print Qt.AlignLeft237238# constructors239a = QSize(12,13)240b = QFont()241242# static method243QDate.currentDate()244245# enum value246QFont.UltraCondensed247248\endcode249250\section Decorators Decorator slots251252PythonQt introduces a new generic approach to extend any wrapped QObject or CPP253object with254255- constructors256- destructors (for CPP objects)257- additional slots258- static slots (callable on both the Meta object and the instances)259260The idea behind decorators is that we wanted to make it as easy as possible to261extend wrapped objects. Since we already have an implementation for invoking any262Qt Slot from Python, it looked promising to use this approach for the extension263of wrapped objects as well. This avoids that the PythonQt user needs to care264about how Python arguments are mapped from/to Qt when he wants to create static265methods, constructors and additional member functions.266267The basic idea about decorators is to create a QObject derived class that268implements slots which take one of the above roles (e.g. constructor, destructor269etc.) via a naming convention. These slots are then assigned to other classes270via the naming convention.271272- QVariant new_SomeClassName(...) - defines a constructor for "SomeClassName"273that returns a QVariant274- SomeClassName* new_SomeClassName(...) - defines a constructor for275"SomeClassName" that returns a new object of type SomeClassName (where276SomeClassName can be any CPP class, not just QObject classes)277- void delete_SomeClassName(SomeClassName* o) - defines a destructor, which278should delete the passed in object o279- anything static_SomeClassName_someMethodName(...) - defines a static method280that is callable on instances and the meta class281- anything someMethodName(SomeClassName* o, ...) - defines a slot that will be282available on SomeClassName instances (and derived instances). When such a slot283is called the first argument is the pointer to the instance and the rest of the284arguments can be used to make a call on the instance.285286The below example shows all kinds of decorators in action:287288\code289290// an example CPP object291class YourCPPObject {292public:293YourCPPObject(int arg1, float arg2) { a = arg1; b = arg2; }294295float doSomething(int arg1) { return arg1*a*b; };296297private:298299int a;300float b;301};302303// an example decorator304class ExampleDecorator : public QObject305{306Q_OBJECT307308public slots:309// add a constructor to QSize variant that takes a QPoint310QVariant new_QSize(const QPoint& p) { return QSize(p.x(), p.y()); }311312// add a constructor for QPushButton that takes a text and a parent widget313QPushButton* new_QPushButton(const QString& text, QWidget* parent=NULL) {314return new QPushButton(text, parent); }315316// add a constructor for a CPP object317YourCPPObject* new_YourCPPObject(int arg1, float arg2) { return new318YourCPPObject(arg1, arg2); }319320// add a destructor for a CPP object321void delete_YourCPPObject(YourCPPObject* obj) { delete obj; }322323// add a static method to QWidget324QWidget* static_QWidget_mouseGrabber() { return QWidget::mouseGrabber(); }325326// add an additional slot to QWidget (make move() callable, which is not327declared as a slot in QWidget) void move(QWidget* w, const QPoint& p) {328w->move(p); }329330// add an additional slot to QWidget, overloading the above move method331void move(QWidget* w, int x, int y) { w->move(x,y); }332333// add a method to your own CPP object334int doSomething(YourCPPObject* obj, int arg1) { return obj->doSomething(arg1);335}336};337338...339340PythonQt::self()->addDecorators(new ExampleDecorator());341PythonQt::self()->registerClass(&QPushButton::staticMetaObject);342PythonQt::self()->registerCPPClassNames(QStringList() << "YourCPPObject");343344\endcode345346After you have registered an instance of the above ExampleDecorator, you can do347the following from Python (all these calls are mapped to the above decorator348slots):349350\code351from PythonQt import *352353# call our new constructor of QSize354size = QSize(QPoint(1,2));355356# call our new QPushButton constructor357button = QPushButton("sometext");358359# call the move slot (overload1)360button.move(QPoint(0,0))361362# call the move slot (overload2)363button.move(0,0)364365# call the static method366grabber = QWidget.mouseWrapper();367368# create a CPP object via constructor369yourCpp = YourCPPObject(1,11.5)370371# call the wrapped method on CPP object372print yourCpp.doSomething(1);373374# destructor will be called:375yourCpp = None376377\endcode378379\section Building380381PythonQt requires at least Qt 4.2.2 (or higher) and Python 2.3, 2.4 and 2.5 on382Windows, Linux and MacOS X. To compile PythonQt, you will need a python383developer installation which includes Python's header files and the384python2x.[lib | dll | so | dynlib].385386For building PythonQt, you will need to set some environment variables:387\b PYTHON_ROOT should point to the Python sources/headers.388\b PYTHON_LIB should point to where the Python library files are located.389\b PYTHONQT_ROOT should point to the root directory of PythonQt.390391Run qmake on PythonQt.pro to generate a project file for your system and then392build it.393394\section Tests395396There is a unit test that tests most features of PythonQt, see the \b tests397subdirectory for details.398399\section Examples400401Examples are available in the \b examples directory. The PyScriptingConsole402implements a simple interactive scripting console that shows how to script a403simple application.404405The following shows how to integrate PythonQt into you Qt application:406407\code408#include "PythonQt.h"409#include <QApplication>410...411412int main( int argc, char **argv )413{414415QApplication qapp(argc, argv);416417// init PythonQt and Python itself418PythonQt::init(PythonQt::IgnoreSiteModule | PythonQt::RedirectStdOut);419420// get a smart pointer to the __main__ module of the Python interpreter421PythonQtObjectPtr mainContext = PythonQt::self()->getMainModule();422423// add a QObject as variable of name "example" to the namespace of the424__main__ module PyExampleObject example;425PythonQt::self()->addObject(mainContext, "example", &example);426427// register all other QObjects that you want to script and that are returned428by your API PythonQt::self()->registerClass(&QMainWindow::staticMetaObject);429PythonQt::self()->registerClass(&QPushButton::staticMetaObject);430...431432// do something433PythonQt::self()->runScript(mainContext, "print example\n");434PythonQt::self()->runScript(mainContext, "def multiply(a,b):\n return435a*b;\n"); QVariantList args; args << 42 << 47; QVariant result =436PythonQt::self()->call(mainContext,"multiply", args);437...438\endcode439440441\section TODOs442443- improve qmake profiles for non mevis users444- add more information on how to distribute an application that uses PythonQt,445including the Python distribution446447*/448449450