我想在文本区域中将Python中的字符串内容(多行)发送到QML应用程序。所以我该怎么做。
test.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
}
}
答案 0 :(得分:1)
如果您要将信息从Python
发送到QML
,则必须创建一个继承自QObject
且具有q-property
的类来存储该值,然后导出该类的对象为QML
setContextProperty()
,QML
侧执行绑定,如下所示:
<强> main.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_())
<强> main.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
}
}