Qt-如何使用 python 将函数连接到 qml 中的信号?使用 QQmlApplicationEngine

Qt-how to connect a function to a signal in qml with python? using QQmlApplicationEngine

这是 qml 文件。 "main.qml"

import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Layouts 1.1

ApplicationWindow{
    visible:true
    width:640
    height:480
    id:window
    title:asTr("editor")

    signal show(string text)



    TextArea{
        text:"hello"
        onTextChanged:show(text);
    }

}

这是 python 代码。 "main.py"

import sys
from PyQt5.QtCore import QObject, QUrl, Qt
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import QQmlApplicationEngine

def show(text):
    print(text)


if __name__ == "__main__":
  app = QApplication(sys.argv)
  engine = QQmlApplicationEngine()
  engine.load('main.qml')
  win = engine.rootObjects()[0]
  win.show()
  sys.exit(app.exec_())

我想将 main.qml 中的信号 "show" 连接到 main.py 中的插槽 "show"。我该怎么做?

首先也是最重要的:不要调用你的信号 showshow 已经是 QWindow 的插槽。如果将名称更改为其他名称,则只需在 python 代码中连接 qml 中定义的信号即可:

qml:

import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Layouts 1.1

ApplicationWindow{
    visible:true
    width:640
    height:480
    id:window
    title: "editor"

    signal textUpdated(string text)


    TextArea{
        text:"hello"
        onTextChanged: textUpdated(text);
    }

}

python:

import sys
from PyQt5.QtCore import QObject, QUrl, Qt
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import QQmlApplicationEngine

def show(text):
    print(text)


if __name__ == "__main__":
  app = QApplication(sys.argv)
  engine = QQmlApplicationEngine()
  engine.load('main.qml')
  win = engine.rootObjects()[0]
  win.textUpdated.connect(show)
  win.show()
  sys.exit(app.exec_())