名为param的PySide2信号

用户

我尝试使用PySide2复制下面的示例。在

https://evileg.com/en/post/242/

但由于PySide2不支持向QML发出带有命名参数的信号,我不知道如何使用PySide2来实现这一点?在

这是我的密码

主.py

from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine
from PySide2.QtCore import QObject, Signal, Slot, Property


class Calculator(QObject):
    def __init__(self):
        QObject.__init__(self)

    sumResult = Signal(int)
    subResult = Signal(int)

    @Slot(int, int)
    def sum(self, arg1, arg2):
        self.sumResult.emit(arg1 + arg2)

    @Slot(int, int)
    def sub(self, arg1, arg2):
        self.subResult.emit(arg1 - arg2)


if __name__ == "__main__":
    import sys

    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()
    calculator = Calculator()
    engine.rootContext().setContextProperty("calculator", calculator)
    engine.load("/code/QML/calc.qml")

    engine.quit.connect(app.quit)
    sys.exit(app.exec_())


已被浏览了8670次
更新日期: 2020-10-26 06:43:11
1 个回答
fefe Tyson

不能这样复制,如果要实现项目,可以让插槽返回值:

主.py

from PySide2 import QtCore, QtGui, QtQml


class Calculator(QtCore.QObject):
    # Slot for summing two numbers
    @QtCore.Slot(int, int, result=int)
    def sum(self, arg1, arg2):
        return arg1 + arg2

    # Slot for subtraction of two numbers
    @QtCore.Slot(int, int, result=int)
    def sub(self, arg1, arg2):
        return arg1 - arg2


if __name__ == "__main__":
    import os
    import sys

    # Create an instance of the application
    app = QtGui.QGuiApplication(sys.argv)
    # Create QML engine
    engine = QtQml.QQmlApplicationEngine()
    # Create a calculator object
    calculator = Calculator()
    # And register it in the context of QML
    engine.rootContext().setContextProperty("calculator", calculator)
    # Load the qml file into the engine
    file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "main.qml")
    engine.load(file)

    engine.quit.connect(app.quit)
    sys.exit(app.exec_())

主.qml

^{pr2}$
评论 - 2020年8月26日 20:44

最新Python问答

推荐Python问答