gpt4 book ai didi

qt - PyQt5 QML信号到Python插槽?

转载 作者:行者123 更新时间:2023-12-04 05:24:29 26 4
gpt4 key购买 nike

python方法/插槽如何连接到QML信号?看起来QtObject.connect()曾经在PyQt4中工作,但它是no longer available in 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事件中继到该对象上的插槽,但是这种方法似乎是round回的。有没有更好的办法?

最佳答案

qml_rectangle.mousePressEvent不是信号,它是在鼠标事件上调用的事件处理程序,因此您无法连接到它。您可以将其替换为处理程序函数(qml_rectangle.mousePressEvent = on_qml_mouse_clicked),但这不是使用Qt的一种非常干净的方法。

更好的方法是在qml文件中定义一个信号,并从矩形的onClicked处理程序中发出该信号:

import QtQuick 2.0

Rectangle {
signal clicked()
MouseArea {
anchors.fill: parent
onClicked: {
parent.clicked() // emit the parent's signal
}
}
}

然后,您可以通过python代码连接到它:
...
def on_qml_mouse_clicked():
print('mouse clicked')

qml_rectangle.clicked.connect(on_qml_mouse_clicked)
...

关于qt - PyQt5 QML信号到Python插槽?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19131084/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com