在 QML 中使用 Python class 个文件

Using Python class files in QML

我有一个 main.qml 文件,如下所示

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5


ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    TextField {
        id:textarea
        anchors.centerIn: parent
        Button {
            text: "Click Me"
            anchors.leftMargin: 34
            id:textareabutton
            y: 0
            anchors.left:textarea.right
            onClicked: {
                someclass.say(textarea.text)
            }
        }
    }
    TextField {
        id:textarea2
        anchors.horizontalCenterOffset: 0
        anchors.topMargin: 37
        anchors.top: textarea.bottom
        anchors.horizontalCenter: textarea.horizontalCenter
    }
    Connections {
        target: someclass

        onToPython : {
            textarea2.text = say
        }
    }
}

我有一个 python class 文件,我在 qtcreator 中使用添加文件选项添加了该文件,当我 运行 main.qml 时出现错误与 classes 相关的未定义如下

qrc:/main.qml:33:5: QML Connections: Cannot assign to non-existent property "onToPython"
qrc:/main.qml:34: ReferenceError: someclass is not defined
qrc:/main.qml:22: ReferenceError: someclass is not defined

我在 Qt 创建器中为 python 配置了 external tools,当我 运行 通过它时,它起作用了。但是当我 运行 main.qml 时它不起作用。我缺少什么,如何使用 python class 文件。

下面是调用 QML 的 python 文件,如果我从 python 运行 它工作,我想 运行 qml 文件并调用这个 class

import sys
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtCore import QObject,pyqtSignal,pyqtSlot

class someclassr(QObject):
    def __init__(self):
        QObject.__init__(self)

    toPython=pyqtSignal(str, arguments=["say"])
    @pyqtSlot(str)
    def say (self,name):
        word= "hi " + name
        self.toPython.emit(word)


app = QGuiApplication(sys.argv)
engine=QQmlApplicationEngine()
classloader=someclassr()
engine.rootContext().setContextProperty('someclass',classloader)
engine.load('main.qml')
engine.quit.connect(app.quit)
sys.exit(app.exec_())

简短回答:QML 和 Python 之间没有内置集成。我不确定为什么有人会认为有,但实际上没有。 Qt Creator 是一个多语言IDE,它对Python 的支持并不意味着QML 和Python 是集成的。

话虽如此,Python类可以轻松integrated with Qt and QML using PyQt。如果您不想依赖 PyQt,您可以通过编写适配器 类 手动集成两者,该适配器 类 调用您的应用程序将 link 使用的 Python 运行时。