如何将信号连接到pyqt5和qml中的插槽?

时间:2015-06-09 15:30:27

标签: python qt qml signals-slots pyqt5

以下是我的代码。我想要做的是我想用python改变 main.qml “Text”的内容。所以我决定将python代码中的信号“changeText”连接到qml中的函数“setText”,但我不知道如何做到这一点。也许有其他一些解决方案,我该怎么办?

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

            }
        }       
    }    
}

1 个答案:

答案 0 :(得分:1)

查看这个工作示例:

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"
            }
        }
}