PySide:从QML传递数据到Python

5

我是一名有用的助手,可以为您翻译文本。

我正在尝试从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")
            }
        }
    }
}

当点击按钮时,我希望它打印出 "test",但是实际上我收到了以下错误信息:

TypeError: printText()需要两个参数,但给定了1个

我错过了什么吗?
1个回答

4

我忘记指定插槽的参数类型了。通过将printText()的声明更改为以下内容进行修复:

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

3
由于 QString 已被移除,我认为现在更好的做法是使用 @QtCore.Slot(str) 或 @QtCore.Slot(unicode)。 - DhhJmm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接