[PyKDE] Re: How to embed Python in C++

Eric Jardim ericjardim at gmail.com
Fri Mar 24 20:40:00 GMT 2006


I found a way of getting Python extended widgets.

I will post here the way I did and I would like to know if this is the
right, easy and safer way of doing this:

Supose this is a QWidget subclass and that I wrote a module called "
MyWidget.py" with "MyWidget" class defined inside of it.

// let's assume that I've already created my QApplication in C++ code.
SomeQWidgetClass::someMethod()
{
    Py_Initialize();
    PyObject* __main__ = PyImport_AddModule("__main__");
    PyObject* scope = PyObject_GetAttrString(__main__, "__dict__");
    PyRun_String("import sip", Py_single_input, scope, scope);
    PyRun_String("from PyQt4 import QtGui", Py_single_input, scope, scope);
    PyRun_String("import MyWidget", Py_single_input, scope, scope);

    // passing this widget as parent
    QString cmd = QString(
       "w = MyWidget.MyWidget(sip.wrapinstance(%1, QtGui.SomeQWidgetClass))"
    ).arg((long)this);
    PyObject* w = PyRun_String(cmd.toStdString().c_str(), Py_single_input,
scope, scope);
    if (!w)
    {
        PyErr_Print();
    }

    PyObject* id = PyRun_String("sip.unwrapinstance(w)", Py_eval_input,
scope, scope);
    QWidget* widget = (QWidget*) PyLong_AsLong(id);
    layout()->addWidget(widget);
    widget->show();
}

Another thing I am worried about is memory management. Is there any special
care that should I take with those Python created objects?

Thanks,

--
Eric Jardim
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.riverbankcomputing.com/pipermail/pyqt/attachments/20060324/d803e76a/attachment.html


More information about the PyQt mailing list