我有一个PySide2
GUI应用程序,带有一个QPushButton
按钮,并连接了一个@Slot
功能。如何与该功能共享数据?
from PySide2.QtCore import Slot
from PySide2.QtWidgets import QApplication, QMainWindow, QWidget, QPushButton, QVBoxLayout
@Slot()
def button_XYZ_callback():
# Function which is executed when the button XYZ is clicked.
# I'd like to access the __main__s context data "parent_data" here.
pass
if __name__ == '__main__':
# parent context data what I want to access (read only)
parent_data = "blub"
application = QApplication(sys.argv)
window = QMainWindow()
central_widget = QWidget()
xyz_button = QPushButton("XYZ", central_widget)
xyz_button.clicked.connect(button_xyz_callback)
layout = QVBoxLayout(central_widget)
layout.addWidget(xyz_button)
window.show()
sys.exit(application.exec_())
答案 0 :(得分:2)
对于每个Python's LEGB rule,可以从parent_data
函数内部访问全局变量button_XYZ_callback
。
但是,如果您希望减少函数对全局变量的依赖,则标准技术是定义一个类,并使用类或实例属性存储全局值之前的内容:
# based on code from https://wiki.qt.io/Qt_for_Python_Tutorial_ClickableButton
import sys
from PySide2 import QtCore, QtWidgets, QtGui
class MyWidget(QtWidgets.QWidget):
def __init__(self, data):
QtWidgets.QWidget.__init__(self)
self.data = data
self.button = QtWidgets.QPushButton("Click me!")
self.text = QtWidgets.QLabel("Hello World")
self.text.setAlignment(QtCore.Qt.AlignCenter)
self.layout = QtWidgets.QVBoxLayout()
self.layout.addWidget(self.text)
self.layout.addWidget(self.button)
self.setLayout(self.layout)
self.button.clicked.connect(self.button_XYZ_callback)
@QtCore.Slot()
def button_XYZ_callback(self):
print(self.data)
if __name__ == "__main__":
parent_data = "blub"
app = QtWidgets.QApplication(sys.argv)
widget = MyWidget(data=parent_data)
widget.show()
sys.exit(app.exec_())
或者,如果在定义回调之前已知道数据,则可以使用函数工厂将数据放入回调的封闭范围内:
import sys
from PySide2.QtCore import Slot
from PySide2.QtWidgets import QApplication, QPushButton
def make_callback(data):
@Slot()
def button_XYZ_callback():
print(data)
return button_XYZ_callback
if __name__ == "__main__":
parent_data = "blub"
# https://wiki.qt.io/Qt_for_Python_Tutorial_ClickableButton
app = QApplication(sys.argv)
button = QPushButton("Click me")
button.clicked.connect(make_callback(parent_data))
button.show()
app.exec_()