PyQt5 QML信号到Python插槽?

时间:2013-10-02 06:25:56

标签: qt pyqt qml pyqt5

如何将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事件中继到该对象上的插槽,但该方法似乎是迂回的。还有更好的方法吗?

2 个答案:

答案 0 :(得分:15)

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)
...

答案 1 :(得分:2)

我建议对 QQuickView 进行子类化,并在其根上下文上设置属性,例如 MainWindow 。现在您需要做的就是在该类中添加函数,例如 @pyqtSlot(' QString'),然后您可以使用 onClicked设置事件处理程序: MainWindow.FunctionName(Arguments_According_To_Decoration)

然后你的 main.py 看起来像这样

#!/bin/env python3
# -*- coding: utf-8 -*-
from PyQt5.QtCore    import pyqtSlot
from PyQt5.QtCore    import QUrl
from PyQt5.QtQuick   import QQuickView
from PyQt5.QtWidgets import QApplication
import sys

class MainWindow(QQuickView):
    def __init__(self):
        super().__init__()
        self.setSource(QUrl('sample.qml'))
        self.rootContext().setContextProperty("MainWindow", self)
        self.show()

    @pyqtSlot('QString')
    def Print(self, value):
        print(value)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWindow()
    sys.exit(app.exec_())

sample.qml 一样

import QtQuick          2.0
import QtQuick.Controls 2.2

Rectangle {
    width: 200; height: 200

    Button {
      text: "print Hello World"
      onClicked: MainWindow.Print('hello world')
    }
}

您可以在文档中找到更多信息

http://pyqt.sourceforge.net/Docs/PyQt5/signals_slots.html