diff --git a/QtQuick/README.md b/QtQuick/README.md index a123d18..253ed41 100644 --- a/QtQuick/README.md +++ b/QtQuick/README.md @@ -2,8 +2,30 @@ - 目录 - [Flat样式](#1Flat样式) + - [QML与Python交互](#2QML与Python交互) ## 1、Flat样式 [运行 FlatStyle.py](FlatStyle.py) -![FlatStyle](ScreenShot/FlatStyle.gif) \ No newline at end of file +![FlatStyle](ScreenShot/FlatStyle.gif) + +## 2、QML与Python交互 +[运行 Signals.py](Signals.py) + +交互的办法有很多种,由于主要界面功能都是有QML来实现,Python只是作为辅助提供部分功能。 +于是和浏览器中js与python交互方式类似,提供一个Python对象给QML访问。 + +1. 通过 `engine.rootContext().setContextProperty('_Window', w)` 注册提供一个Python对象 +2. Python对象中被访问的方法前面使用装饰器 `@pyqtSlot`,比如: `@pyqtSlot(int)` 或者 `@pyqtSlot(str, result=str) # 可以获取返回值` 。 +3. QML中的信号或者Python对象中的信号都可以互相绑定对方的槽函数 +```js +Component.onCompleted: { + // 绑定信号槽到python中的函数 + valueChanged.connect(_Window.onValueChanged) + // 绑定python中的信号到qml中的函数 + _Window.timerSignal.connect(appendText) +} +``` + + +![Signals](ScreenShot/Signals.gif) diff --git a/QtQuick/ScreenShot/Signals.gif b/QtQuick/ScreenShot/Signals.gif new file mode 100644 index 0000000..23ee874 Binary files /dev/null and b/QtQuick/ScreenShot/Signals.gif differ diff --git a/QtQuick/Signals.py b/QtQuick/Signals.py index 812b628..3ea5b81 100644 --- a/QtQuick/Signals.py +++ b/QtQuick/Signals.py @@ -10,9 +10,10 @@ Created on 2019年9月18日 @description: 信号槽 """ +from time import time import sys -from PyQt5.QtCore import QCoreApplication, Qt, pyqtSlot +from PyQt5.QtCore import QCoreApplication, Qt, pyqtSlot, pyqtSignal, QTimer from PyQt5.QtQml import QQmlApplicationEngine from PyQt5.QtWidgets import QApplication, QMessageBox, QWidget, QVBoxLayout,\ QPushButton, QTextBrowser @@ -37,7 +38,9 @@ ApplicationWindow { Component.onCompleted: { // 绑定信号槽到python中的函数 - valueChanged.connect(_Window.onValueChanged); + valueChanged.connect(_Window.onValueChanged) + // 绑定python中的信号到qml中的函数 + _Window.timerSignal.connect(appendText) } function appendText(text) { @@ -82,6 +85,9 @@ ApplicationWindow { class Window(QWidget): + # 定义一个时间信号 + timerSignal = pyqtSignal(str) + def __init__(self, *args, **kwargs): super(Window, self).__init__(*args, **kwargs) layout = QVBoxLayout(self) @@ -89,6 +95,12 @@ class Window(QWidget): self, clicked=self.callQmlFunc)) self.resultView = QTextBrowser(self) layout.addWidget(self.resultView) + self._timer = QTimer(self, timeout=self.onTimeout) + self._timer.start(2000) + + def onTimeout(self): + # 定时器发送信号通知qml + self.timerSignal.emit('定时器发来:' + str(time())) def callQmlFunc(self): # 主动调用qml中的appendText函数 diff --git a/README.md b/README.md index 6ea6cf9..1a1e372 100644 --- a/README.md +++ b/README.md @@ -147,6 +147,7 @@ https://pyqt5.com 社区是专门针对PyQt5学习和提升开设的博客网站 - [QtQuick](QtQuick) - [Flat样式](QtQuick/FlatStyle.py) + - [QML与Python交互](QtQuick/Signals.py) - [QChart](QChart) - [折线图](QChart/LineChart.py)