在QML中使用Python类文件

问题描述 投票:0回答:1

我有一个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类文件,我在qtcreator使用添加文件选项添加,当我运行main.qml我得到错误相关的类未定义如下

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类文件。

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

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_())
python qt pyqt qml qt-creator
1个回答
1
投票

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

话虽如此,Python类可以很容易integrated with Qt and QML using PyQt。如果您不想依赖PyQt,可以通过编写调用应用程序将链接的Python运行时的适配器类来手动集成这两者。

© www.soinside.com 2019 - 2024. All rights reserved.