python - 如何在 PyQt 中向事件循环发出自定义事件
问题描述
我正在尝试在 PyQt 中发出自定义事件。一个小部件会发出,另一个小部件会监听事件,但这两个小部件不需要相关。
在 JavaScript 中,我会通过这样做来实现这一点
// Component 1
document.addEventListener('Hello', () => console.log('Got it'))
// Component 2
document.dispatchEvent(new Event("Hello"))
编辑:我知道信号和插槽,但只知道如何在父母和孩子之间使用它们。我将如何在任意不相关的小部件之间使用这种机制(或其他机制)?
解决方案
在 PyQt 中,以下指令:
document.addEventListener('Hello', () => console.log('Got it'))
是等价的
document.hello_signal.connect(lambda: print('Got it'))
以类似的方式:
document.dispatchEvent(new Event("Hello"))
是等价的
document.hello_signal.emit()
但最大的区别是“文档”对象的范围,因为连接是在全局元素之间。但在 PyQt 中,该元素不存在。
模拟您指出的行为的一种方法是创建一个全局对象:
全局对象.py
from PyQt5 import QtCore
import functools
@functools.lru_cache()
class GlobalObject(QtCore.QObject):
def __init__(self):
super().__init__()
self._events = {}
def addEventListener(self, name, func):
if name not in self._events:
self._events[name] = [func]
else:
self._events[name].append(func)
def dispatchEvent(self, name):
functions = self._events.get(name, [])
for func in functions:
QtCore.QTimer.singleShot(0, func)
主文件
from PyQt5 import QtCore, QtWidgets
from globalobject import GlobalObject
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
button = QtWidgets.QPushButton(text="Press me", clicked=self.on_clicked)
self.setCentralWidget(button)
@QtCore.pyqtSlot()
def on_clicked(self):
GlobalObject().dispatchEvent("hello")
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
GlobalObject().addEventListener("hello", self.foo)
self._label = QtWidgets.QLabel()
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(self._label)
@QtCore.pyqtSlot()
def foo(self):
self._label.setText("foo")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w1 = MainWindow()
w2 = Widget()
w1.show()
w2.show()
sys.exit(app.exec_())
推荐阅读
- python - 使用curve_fit进行多元高斯拟合的问题
- python - 如何拆分具有多个定界符的字符串,但每个定界符仅一次?Python
- reactjs - React-Bootstrap 轮播滑块:如何检测显示中的当前幻灯片
- mongodb - 使用 mongoimport 时,可以指定 _id 应该是 UUID 吗?
- javascript - 如何使用字典在 JavaScript 返回值中实现回调
- c++ - 参考偏移量中看似无关的规范
- c# - 如何以管理员身份使用windows服务启动软件?
- html - 里面的引号
显示为“”或类似字符的元素
- visual-studio - 调试和构建 Web 成功但发布失败视觉 2019
- azure-log-analytics - T-SQL queries in Azure Log Analytics Workspaces?