python 方法/槽如何连接到 QML 信号?看起来 QtObject.connect() 曾经在 PyQt4 中工作,但在 PyQt5 中不再可用。
#Sample QML File (stack.qml)
import QtQuick 2.0
Rectangle {
MouseArea {
anchors.fill: parent
onClicked: {
// relay this to python
}
}
}
--
#Sample Python File
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQuick import QQuickView
if __name__ == '__main__':
import os
import sys
app = QGuiApplication(sys.argv)
view = QQuickView()
view.setWidth(500)
view.setHeight(500)
view.setTitle('Hello PyQt')
view.setResizeMode(QQuickView.SizeRootObjectToView)
view.setSource(QUrl.fromLocalFile(os.path.join(os.path.dirname(__file__),'stack.qml')))
def on_qml_mouse_clicked(mouse_event):
print 'mouse clicked'
view.show()
qml_rectangle = view.rootObject()
# this technique doesn't work #############################
qml_rectangle.mousePressEvent.connect(on_qml_mouse_clicked)
sys.exit(app.exec_())
一些 PyQT 示例通过“setContextProperty”将对象传递到 QML 上下文中,然后将 QML 事件中继到该对象上的插槽,但这种方法似乎是迂回的。有没有更好的办法?