[PyKDE] Typecasting problems with PyQt embedded in Scribus

Jim Bublitz jbublitz at nwinternet.com
Thu Jun 30 05:07:30 BST 2005

On Wednesday 29 June 2005 19:34, Henning Schröder wrote:
> Hi!
> Scribus is a free DTP application which is coded in C++ and Qt and
> provides scripting
> with Python.
> A Python script can import the qt module and access the data from the
> running application as far as it is reachable with the Qt-object
> system (qApp.children(), ..)
> Unfortunately automatic typecasting does not always work as expected.
> For example when I access qt.qApp.mainWidget() I get a QWidget. But
> the main widget is a ScribusWin-class which is derived from
> QMainWindow. So I expected  I can get a QMainWindow.
> Instead of writing my own SIP-wrapper for ScribusWin I would like
> better typecasting.
> Is this possible or can I do it manually?

In the C++ program do something like

  PyObject *mainWinPtr = PyLong_FromLong ((long)(QMainWindow *) 

and pass that as one of the arguments when calling into Python.


In the Python program do:

from sip import wrapinstance, unwrapinstance
from qt import QMainWindow

def methodToBeCalledFromCPP (mainWinPtr):
  mainWin = wrapinstance (mainWinPtr, QMainWindow)
  # Python will recognize mainWin as type QMainWindow
  # and will use the instance passed (as a ptr/long) from
  # C++

  result = ... # some Qt object
  return unwrapinstance (result)  # returns a C++ pointer  as long


Back in C++:

 // pyResult is the long returned from the call to Python
 // returned as a PyObject then converted to a pointer
 // the Qt object it points to

 // the instance can be created either in C++ or Python
 // (but of course you have make sure the Python instance
 // is persistent, as a widget owned by QMainWindow would be,
 // for example).

  QSomething *qobject = PyLong_AsLong (pyResult); 

You can do the above with any objects that have sip bindings. If you want a 
ScribusWin object in Python, you need to bind it first, but PyQt already 
binds QMainWindow.

wrapinstance and unwrapinstance are covered in the sip docs.


More information about the PyQt mailing list