[Solved] PySide: passing data from QML to Python
-
I want to send data from QML to Python. The QML has a button, that when clicked will call a slot with a hardcoded string as parameter. This slot should print the string sent from the QML.
@#!/usr/bin/env python
import sys
from PySide import QtCore, QtGui, QtDeclarativeclass Test( QtCore.QObject ):
def init( self ):
QtCore.QObject.init(self)@QtCore.Slot() def printText(self,text): print text
class MainWindow( QtDeclarative.QDeclarativeView ):
def init( self, parent=None ):
super( MainWindow, self ).init( parent )
self.setWindowTitle( "Test" )
self.setSource( QtCore.QUrl.fromLocalFile( './test.qml' ) )
self.setResizeMode( QtDeclarative.QDeclarativeView.SizeRootObjectToView )app = QtGui.QApplication( sys.argv )
window = MainWindow()
context = window.rootContext()
context.setContextProperty("testModel",Test())
window.show()
sys.exit( app.exec_() )@test.qml:
@import QtQuick 1.0
Rectangle {
width: 200
height: 200
color: "white"Rectangle { anchors.centerIn: parent width: 100 height: 50 color: "black" Text { anchors.centerIn: parent text: "click" color: "white" } MouseArea { anchors.fill: parent onClicked: { testModel.printText("test") } } }
}@
When I click the button, the following error occurs:
@TypeError: printText() takes exactly 2 arguments (1 given)@
What am I doing wrong?
-
I figured it out. I forgot to specify the slot's argument type. Fixed it by changing the slot's declaration to this:
@@QtCore.Slot('QString')
def printText(self,text):
print text@