What is the method for transferring data to a subwindow in PyQt5?
In PyQt5, you can achieve data transfer between sub-windows by using the signal and slot mechanism. The specific steps are as follows:
- Create a signal class to pass data. Add a signal object in the subclass, for example: dataChanged = QtCore.pyqtSignal(str)
- When data needs to be passed in the child window, use a signal object to emit a signal, for example: self.dataChanged.emit(data)
- Connect the signal and slot of the child window in the main window. After creating the child window object, use the connect() method to connect the signal of the child window to the slot function of the main window, for example: subwindow.dataChanged.connect(self.handleDataChanged)
- Define a slot function in the main window to receive data passed from the child window, for example: def handleDataChanged(self, data):
In this way, when the child window sends a signal, the slot function in the main window will be called, allowing the data to be retrieved and processed within the slot function.
The complete example code is as follows:
from PyQt5 import QtCore, QtGui, QtWidgets
class SubWindow(QtWidgets.QMainWindow):
dataChanged = QtCore.pyqtSignal(str)
def __init__(self):
super().__init__()
self.button = QtWidgets.QPushButton("传递数据", self)
self.button.clicked.connect(self.sendData)
def sendData(self):
data = "Hello World"
self.dataChanged.emit(data)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.subwindow = SubWindow()
self.subwindow.dataChanged.connect(self.handleDataChanged)
def handleDataChanged(self, data):
print(data)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
In this example, when the button in the child window is clicked, it will emit a dataChanged signal with the string “Hello World”. The slot function handleDataChanged in the main window will receive this signal and print out the passed data.