pyqt5 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);
}
}
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_())
代码如上,我想用python代码中的show方法和qml文件中的show信号连接起来,我该怎么做呢?
二次元信徒
9 years, 7 months ago
Answers
写在qml里,我用C++的代码作为例子,python的做法应该是类似的,首先把C++对象(或python对象)暴露给qml:
engine.rootContext()->setContextProperty("myContext", myContext);
myContext要继承QObject,然后在qml里connect,如:
ApplicationWindow {
title: qsTr("Hello World")
width: 640
height: 480
visible: true
signal show(string text)
Component.onCompleted: {
show.connect(myContext.print);
}
...
}
yuaisyu
answered 9 years, 7 months ago