2012-11-17 89 views
4

我試圖從QML發送數據到Python,但我得到一個錯誤。PySide:將數據從QML傳遞到Python

test.py:

#!/usr/bin/env python 

import sys 
from PySide import QtCore, QtGui, QtDeclarative 

class 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") 
      } 
     } 
    } 
} 

當單擊該按鈕,我希望它打印 「測試」,而是我得到這個錯誤:

TypeError: printText() takes exactly 2 arguments (1 given)

我錯過了什麼?

編輯:將示例更改爲更簡單的示例。

回答

3

我忘了指定插槽的參數類型。通過改變printText()的聲明,這個固定:

@QtCore.Slot('QString') 
def printText(self,text): 
    print text 
+3

由於QString的已被刪除,我認爲這將是更好的現在:@ QtCore.Slot(STR)或@ QtCore.Slot(UNICODE) –