How to call python method from qml in pyqt


http://doc.qt.nokia.com/4.7-snapshot/qtbinding.html
// MyItem.qml
 import QtQuick 1.0
 Item {
     width: 100; height: 100
     MouseArea {
         anchors.fill: parent
         onClicked: {
             myObject.cppMethod("Hello from QML")
             myObject.cppSlot(12345)
         }
     }
 }
//mainWidget.py
import sip
sip.setapi('QString',2)
sip.setapi('QVariant',  2)
from PyQt4.QtCore import *
from PyQt4.QtDeclarative import *
from PyQt4.QtGui import *
import sys
import os
class MyObject(QObject):
    def __init__(self, parent=None):
        super(MyObject, self).__init__(parent)
    @pyqtSlot(str)
    def cppMethod(self, msg):
        print "call the c++ method with ",msg
    @pyqtSlot(int)
    def cppSlot(self, number):
        print "call the c++ slot with", number  
                      
if __name__ == '__main__':
    app = QApplication(sys.argv)
    view = QDeclarativeView()
    myclass = MyObject()
    view.rootContext().setContextProperty("myObject",myclass)
    view.setSource(QUrl("MyItem.qml"))
    view.show()
    sys.exit(app.exec_())

댓글