Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you return an object from python to QML?

I'm trying to return a QObject from a Slot. I'm using PySide and QML. My code looks like this:

class myClass(QtCore.QObject):
    def __init__(self):
        self.object = QtCore.QObject()

    QtCore.Slot(result=object)
    def myFunc(self):
        return self.object

When I console.log the return value I get:

QVariant(PySide::PyObjectWrapper)

I can't seem to get the value out of this thing. Can somebody point me in the right direction? I can return primitive types (like int, str, etc.), but objects, lists, and dicts are beyond me. Any help would be greatly appreciated.

EDIT

I am trying to access properties of an object using dot notation. If somebody could show me an example of this, it would be very helpful. However, if I could just get the object back I think I could go the distance by myself. Thanks again!

Thanks

Jack

like image 413
Jack Benson Avatar asked Aug 14 '26 01:08

Jack Benson


1 Answers

So, here is something that does what I think you're trying to do. When you click anywhere, the blue area changes green. This is done by changing the color property on the object that is passed by a signal.

#!/usr/bin/env python

import sys
from PySide import QtCore
from PySide.QtGui import QApplication
from PySide.QtDeclarative import QDeclarativeView
from PySide.QtOpenGL import QGLWidget

def some_function(passed_object):
    passed_object.setProperty("color", "green")

def main(argv):
    app = QApplication(argv)

    display_widget = QDeclarativeView()
    display_widget.setViewport(QGLWidget())

    display_widget.setResizeMode(QDeclarativeView.SizeRootObjectToView)
    display_widget.setSource(QtCore.QUrl('pass_an_object.qml'))

    display_widget.rootObject().object_signal.connect(some_function)

    display_widget.show()
    display_widget.resize(640,480)

    sys.exit(app.exec_())

if __name__ == '__main__':
    main(sys.argv)

With the accompanying qml file (I've called it pass_an_object.qml):

import QtQuick 1.0

Rectangle {
    id: foo
    width: 640
    height: 640
    color: "red"

    signal object_signal(variant foo)

    Rectangle {
        id: an_object
        width: 100
        height: 100
        color: "blue"
    }

    MouseArea {
        anchors.fill: parent
        onClicked: {
            object_signal(an_object)
        }

    }
}
like image 175
Henry Gomersall Avatar answered Aug 16 '26 15:08

Henry Gomersall