Skip to content

Commit 7526182

Browse files
committed
QML与Python交互
1 parent 5a1901b commit 7526182

File tree

4 files changed

+38
-3
lines changed

4 files changed

+38
-3
lines changed

QtQuick/README.md

+23-1
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,30 @@
22

33
- 目录
44
- [Flat样式](#1Flat样式)
5+
- [QML与Python交互](#2QML与Python交互)
56

67
## 1、Flat样式
78
[运行 FlatStyle.py](FlatStyle.py)
89

9-
![FlatStyle](ScreenShot/FlatStyle.gif)
10+
![FlatStyle](ScreenShot/FlatStyle.gif)
11+
12+
## 2、QML与Python交互
13+
[运行 Signals.py](Signals.py)
14+
15+
交互的办法有很多种,由于主要界面功能都是有QML来实现,Python只是作为辅助提供部分功能。
16+
于是和浏览器中js与python交互方式类似,提供一个Python对象给QML访问。
17+
18+
1. 通过 `engine.rootContext().setContextProperty('_Window', w)` 注册提供一个Python对象
19+
2. Python对象中被访问的方法前面使用装饰器 `@pyqtSlot`,比如: `@pyqtSlot(int)` 或者 `@pyqtSlot(str, result=str) # 可以获取返回值`
20+
3. QML中的信号或者Python对象中的信号都可以互相绑定对方的槽函数
21+
```js
22+
Component.onCompleted: {
23+
// 绑定信号槽到python中的函数
24+
valueChanged.connect(_Window.onValueChanged)
25+
// 绑定python中的信号到qml中的函数
26+
_Window.timerSignal.connect(appendText)
27+
}
28+
```
29+
30+
31+
![Signals](ScreenShot/Signals.gif)

QtQuick/ScreenShot/Signals.gif

194 KB
Loading

QtQuick/Signals.py

+14-2
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,10 @@
1010
@description: 信号槽
1111
"""
1212

13+
from time import time
1314
import sys
1415

15-
from PyQt5.QtCore import QCoreApplication, Qt, pyqtSlot
16+
from PyQt5.QtCore import QCoreApplication, Qt, pyqtSlot, pyqtSignal, QTimer
1617
from PyQt5.QtQml import QQmlApplicationEngine
1718
from PyQt5.QtWidgets import QApplication, QMessageBox, QWidget, QVBoxLayout,\
1819
QPushButton, QTextBrowser
@@ -37,7 +38,9 @@
3738
3839
Component.onCompleted: {
3940
// 绑定信号槽到python中的函数
40-
valueChanged.connect(_Window.onValueChanged);
41+
valueChanged.connect(_Window.onValueChanged)
42+
// 绑定python中的信号到qml中的函数
43+
_Window.timerSignal.connect(appendText)
4144
}
4245
4346
function appendText(text) {
@@ -82,13 +85,22 @@
8285

8386
class Window(QWidget):
8487

88+
# 定义一个时间信号
89+
timerSignal = pyqtSignal(str)
90+
8591
def __init__(self, *args, **kwargs):
8692
super(Window, self).__init__(*args, **kwargs)
8793
layout = QVBoxLayout(self)
8894
layout.addWidget(QPushButton('Python调用qml中的函数',
8995
self, clicked=self.callQmlFunc))
9096
self.resultView = QTextBrowser(self)
9197
layout.addWidget(self.resultView)
98+
self._timer = QTimer(self, timeout=self.onTimeout)
99+
self._timer.start(2000)
100+
101+
def onTimeout(self):
102+
# 定时器发送信号通知qml
103+
self.timerSignal.emit('定时器发来:' + str(time()))
92104

93105
def callQmlFunc(self):
94106
# 主动调用qml中的appendText函数

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@ https://pyqt5.com 社区是专门针对PyQt5学习和提升开设的博客网站
147147

148148
- [QtQuick](QtQuick)
149149
- [Flat样式](QtQuick/FlatStyle.py)
150+
- [QML与Python交互](QtQuick/Signals.py)
150151

151152
- [QChart](QChart)
152153
- [折线图](QChart/LineChart.py)

0 commit comments

Comments
 (0)