简体   繁体   中英

how to connect the signal to slot in pyqt5 and qml?

following is my codes. what i want to do is that i want to change the content of "Text" in main.qml with python. so i decide to connect the signal "changeText" in python code to the function "setText" in qml,but i don't konw how to do this. Maybe there are some other solutions,what should i do ?

main.py

import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import *  

class MyClass(QObject):
    changeText=pyqtSignal(str)

    def __init__(self):
        super().__init__()


if __name__ == "__main__":
  app = QApplication(sys.argv)
  engine = QQmlApplicationEngine()

  con=MyClass()
  ctx = engine.rootContext()
  ctx.setContextProperty("con", con)


  engine.load('main.qml')

  win = engine.rootObjects()[0]

  con.changeText.connect(win.setText)

  win.show()
  sys.exit(app.exec_())

main.qml

import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Layouts 1.1
import QtQuick.Controls.Styles 1.3

ApplicationWindow{
        visible:true
        width:940
        height:680
        id:root
        title:"markdwon editor"
    Rectangle{
        Text{               
            text:"hello"
            function setText(content)
            {
                text=content

            }
        }       
    }    
}

Check out this working example:

main.py

import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import *


class MyClass(QObject):
    changeText = pyqtSignal(str)

    def __init__(self, parent=None):
        super(MyClass, self).__init__(parent)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    my_obj = MyClass()

    timer = QTimer()
    timer.start(2000)

    engine = QQmlApplicationEngine()
    ctx = engine.rootContext()
    ctx.setContextProperty("my_obj", my_obj)
    engine.load('main.qml')
    root = engine.rootObjects()[0]
    timer.timeout.connect(root.setText)
    sys.exit(app.exec_())

main.qml

import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Layouts 1.1
import QtQuick.Controls.Styles 1.3

ApplicationWindow{

        visible:true
        width:940
        height:680

        id:root

        title: "markdwon editor"

        function setText()
        {
            exampleId.text = Math.random();
        }

        Rectangle{

            Text{
                id:exampleId
                text:"hello"
            }
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM