具有指定参数的PySide2信号

时间:2018-07-29 15:36:10

标签: python pyside2

我正在尝试使用PySide2复制以下示例。

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

但是由于PySide2不支持向QML发出带有命名参数的信号,所以我不知道如何使用PySide2做到这一点?

这是我的代码

main.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_())

1 个答案:

答案 0 :(得分:1)

您不能像这样复制它,如果要实施项目,可以使插槽返回值:

main.py

int.TryParse(comboBox1.Value, out result)

main.qml

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


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

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


if __name__ == "__main__":
    import sys

    # Create an instance of the application
    app = QGuiApplication(sys.argv)
    # Create QML engine
    engine = 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
    engine.load("main.qml")

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