Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PyObject wrapper #27

Merged
merged 9 commits into from
Oct 8, 2014
Prev Previous commit
Next Next commit
Access attributes of Python objects.
  • Loading branch information
Dennis Tomas committed Sep 30, 2014
commit 4f5edd724755c1cdfc0684387dcfd6159995c19e
6 changes: 6 additions & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,12 @@ imported modules using:
If a JavaScript exception occurs in the callback, the :func:`error`
signal is emitted with ``traceback`` containing the exception info.

Attributes on Python objects can be accessed using :func:`getattr`:

.. function:: getattr(obj, string attr) -> var

Get the attribute ``attr`` of the Python object ``obj``.

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:
Expand Down
28 changes: 28 additions & 0 deletions src/qpython.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,34 @@ QPython::callMethod_sync(QVariant obj, QString method, QVariant args)
return v;
}

QVariant
QPython::getattr(QVariant obj, QString attr) {
priv->enter();
PyObject *pyobj = convertQVariantToPyObject(obj);

if (pyobj == NULL) {
emit error(QString("Failed to convert %1 to python object: '%1' (%2)").arg(obj.toString()).arg(priv->formatExc()));
priv->leave();
return QVariant();
}

QByteArray byteArray = attr.toUtf8();
const char *attrStr = byteArray.data();

PyObject *o = PyObject_GetAttrString(pyobj, attrStr);

if (o == NULL) {
emit error(QString("Attribute not found: '%1' (%2)").arg(attr).arg(priv->formatExc()));
priv->leave();
return QVariant();
}

QVariant v = convertPyObjectToQVariant(o);
Py_DECREF(o);
priv->leave();
return v;
}

void
QPython::finished(QVariant result, QJSValue *callback)
{
Expand Down
21 changes: 21 additions & 0 deletions src/qpython.h
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,27 @@ class QPython : public QObject {
QString func,
QVariant args=QVariantList());

/**
* \brief Get an attribute value of a Python object synchronously
*
* \code
* Python {
* Component.onCompleted: {
* importModule('datetime', function() {
* call('datetime.datetime.now', [], function(dt) {
* console.log('Year: ' + getattr(dt, 'year'));
* });
* });
* }
* }
* \endcode
*
* \arg obj The Python object
* \arg attr The attribute to get
* \result The attribute value
**/
Q_INVOKABLE QVariant
getattr(QVariant obj, QString attr);

/**
* \brief Get the PyOtherSide version
Expand Down