【问题标题】:PySide: passing data from QML to PythonPySide:将数据从 QML 传递到 Python
【发布时间】:2012-11-05 18:37:14
【问题描述】:

我正在尝试将数据从 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() 只需要 2 个参数(给定 1 个)

我错过了什么?

编辑:将示例更改为更简单的示例。

【问题讨论】:

    标签: python qt qml pyside qtdeclarative


    【解决方案1】:

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

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

    【讨论】:

    • 由于 QString 已被删除,我认为现在会更好:@QtCore.Slot(str) 或 @QtCore.Slot(unicode)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多