PyQt中窗口中央面板间的数据传递实现问题
解决方案
要实现从第一个窗口中央面板向第二个窗口中央面板传递数据,核心是让第二个窗口的构造函数接收数据,再将数据传递给它的中央面板。以下是修正后的完整代码:
主窗口代码(修正版)
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QLabel, QPushButton, QVBoxLayout, QStyleFactory class CenterPanel(QWidget): def __init__ (self, parent): super().__init__(parent) self.label = QLabel("Window 1") self.dataLabel = QLabel("Data to be passed") self.submitBtn = QPushButton("Open Second Window") self.submitBtn.clicked.connect(self.openSecondwindow) # 绑定按钮点击事件 self.box = QVBoxLayout() self.box.addWidget(self.label) self.box.addWidget(self.dataLabel) self.box.addWidget(self.submitBtn) self.setLayout(self.box) # 修正拼写错误 def openSecondwindow(self): data = self.dataLabel.text() # 正确实例化SecondWindow并传入数据 self.window = SecondWindow(data) self.window.show() class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Project List") WinLeft = 100 WinTop = 100 WinWidth = 200 WinHeight = 150 self.setGeometry(WinLeft, WinTop, WinWidth, WinHeight) self.CenterPane = CenterPanel(self) self.setCentralWidget(self.CenterPane) self.setStyle(QStyleFactory.create("Cleanlooks")) self.setStyleSheet( "background-color: turquoise;" "padding: 0;" "margin: 0;" ) if __name__ == "__main__": app = QApplication([]) main_window = MainWindow() main_window.show() app.exec()
第二个窗口代码(修正版)
from PyQt5.QtWidgets import QMainWindow, QWidget, QLabel, QVBoxLayout, QStyleFactory class CenterPanel(QWidget): def __init__ (self, parent, data): # 添加data参数接收传递的数据 super().__init__(parent) self.label = QLabel("Data to be set in the label below") self.dataLabel = QLabel() if data: self.dataLabel.setText(data) else: self.dataLabel.setText("I have not changed! Data is not passed over!") self.box = QVBoxLayout() self.box.addWidget(self.label) self.box.addWidget(self.dataLabel) self.setLayout(self.box) # 修正拼写错误 class SecondWindow(QMainWindow): def __init__(self, data): # 添加data参数接收来自主窗口的数据 super().__init__() self.setWindowTitle("Second Window") WinLeft = 200 WinTop = 200 WinWidth = 200 WinHeight = 150 self.setGeometry(WinLeft, WinTop, WinWidth, WinHeight) # 将数据传递给中央面板 self.CenterPane = CenterPanel(self, data) self.setCentralWidget(self.CenterPane) self.setStyle(QStyleFactory.create("Cleanlooks")) self.setStyleSheet( "background-color: turquoise;" "padding: 0;" "margin: 0;" ) if __name__ == "__main__": from PyQt5.QtWidgets import QApplication app = QApplication([]) second_window = SecondWindow("Test Data") second_window.show() app.exec()
关键修改说明
- 修正了原代码中的
setLaytou拼写错误,改为正确的setLayout - 给第一个窗口的按钮绑定了点击事件,触发打开第二个窗口的方法
- 修改
SecondWindow的构造函数,添加data参数接收来自主窗口的数据 - 修改第二个窗口的
CenterPanel构造函数,添加data参数,用于设置标签文本 - 在主窗口的
openSecondwindow方法中,正确实例化SecondWindow并传入要传递的数据
这样就实现了从第一个窗口中央面板→主窗口→第二个窗口→第二个窗口中央面板的数据传递流程。
内容的提问来源于stack exchange,提问作者calbeeguy
相关产品推荐
相关产品推荐

