Skip to main content
 首页 » 编程设计

python之如何将文本文件(或字符串发送到 QML 中的 textArea)从 python 到 QML 应用程序

2024年12月31日25pander-it

我想将字符串内容(多行)从 Python 发送到文本区域中的 QML 应用程序。那么我该怎么做。

测试.py

def send_file(file_content) 
    pass // send file to QML text area 

test.qml

Window { 
    id: mainWindow 
    property alias text: textArea.text 
 
    function read_file(){ 
        mainWindow.text = send_file(file_content) //Strings from python 
    } 
 
    TextArea{ 
         id: textArea 
    } 
} 

请您参考如下方法:

如果你想从 Python 发送信息到 QML 你必须创建一个继承自 QObject 的类并且有一个 q -property 存储该值,然后使用 setContextProperty() 将该类的对象导出到 QML,并在 QML 上一边它执行绑定(bind),如继续所示:

主.py

import sys 
 
from PyQt5.QtCore import QObject, pyqtSignal, pyqtProperty, QUrl 
from PyQt5.QtGui import QGuiApplication 
from PyQt5.QtQml import QQmlApplicationEngine 
 
 
class Helper(QObject): 
    textChanged = pyqtSignal() 
 
    def __init__(self, parent=None): 
        QObject.__init__(self, parent) 
        self._text = "" 
 
    @pyqtProperty(str, notify=textChanged) 
    def text(self): 
        return self._text 
 
    @text.setter 
    def text(self, v): 
        if self._text == v: 
            return 
        self._text = v 
        self.textChanged.emit() 
 
    def send_file(self, file_content): 
        self.text = file_content 
 
if __name__ == "__main__": 
    app = QGuiApplication(sys.argv) 
 
    engine = QQmlApplicationEngine() 
    helper = Helper() 
    engine.rootContext().setContextProperty("helper", helper) 
    engine.load(QUrl.fromLocalFile('main.qml')) 
    if not engine.rootObjects(): 
        sys.exit(-1) 
 
    helper.send_file("Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ornare magna felis. Nulla justo ipsum, finibus eu nibh quis, iaculis malesuada lorem. Phasellus et lacus malesuada, aliquam enim condimentum, efficitur sapien. Sed ultricies egestas massa, nec sodales neque mattis et. Praesent euismod pretium hendrerit. Maecenas non porttitor velit, non scelerisque quam. Phasellus at diam vel enim venenatis vulputate sed a nisl. Sed erat nunc, maximus varius justo vitae, vehicula porttitor enim. Maecenas vitae sem odio. Nunc interdum sapien vitae magna tempus, nec laoreet elit placerat. Nullam cursus metus facilisis pulvinar auctor.") 
    sys.exit(app.exec_()) 

ma​​in.qml

import QtQuick 2.10 
import QtQuick.Window 2.2 
import QtQuick.Controls 1.4 
 
Window { 
    id: mainWindow 
    visible: true 
 
    TextArea{ 
         id: textArea 
         anchors.fill: parent 
         text: helper.text 
    } 
}