Connect QML signal to PySide2 slot

泪湿孤枕 提交于 2019-12-20 04:23:47

问题


I have some expirience using Qt/C++ and now I want to switch to PySide2 + QML. I want to connect ui signals, such as clicking a button, to python slot

I have seen many examples, but they all differ, i guess PyQt/PySide is changing quickly now

Can you provide me modern and clean way of connecting a QML signal to PySide Slot? For example clicking a Button to printing some text in python console. Here's my simple code example

main.py

from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine

def test_slot(string): # pseudo slot
    print(string)

if __name__ == "__main__":
    app = QGuiApplication()
    engine = QQmlApplicationEngine('main.qml')
    exit(app.exec_())

main.qml

import QtQuick 2.13
import QtQuick.Controls 2.13

ApplicationWindow {
    visible: true

    Button {
        anchors.centerIn: parent
        text: "Example"
        onClicked: test_slot("Test") //pseudo signal
    }
}

回答1:


The best practice in these cases is to create a QObject, export it to QML and make the connection there as it is also done in C++.

main.py

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


class Foo(QObject):
    @Slot(str)
    def test_slot(self, string):
        print(string)


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

    app = QGuiApplication()
    foo = Foo()
    engine = QQmlApplicationEngine()
    engine.rootContext().setContextProperty("foo", foo)
    qml_file = "main.qml"
    current_dir = os.path.dirname(os.path.realpath(__file__))
    filename = os.path.join(current_dir, qml_file)
    engine.load(QUrl.fromLocalFile(filename))
    if not engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec_())

main.qml

import QtQuick 2.13
import QtQuick.Controls 2.13

ApplicationWindow {
    visible: true

    Button {
        anchors.centerIn: parent
        text: "Example"
        onClicked: foo.test_slot("Test")
    }
}

Note: All C++/QML good practices also apply in Python/QML with minimal changes and restrictions.



来源:https://stackoverflow.com/questions/57619227/connect-qml-signal-to-pyside2-slot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!