通过信号发送
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QPushButton, QLineEdit
from PySide6.QtCore import Signal, Slot
class Mywindow(QWidget):
sendValueSignal = Signal(str) # 0.创建一个信号,并且带一个字符串类型参数
def __init__(self):
super().__init__()
self.mainLayout = QVBoxLayout()
self.label = QLabel('IP:')
self.IPLineEdit = QLineEdit()
self.mainLayout.addWidget(self.label)
self.mainLayout.addWidget(self.IPLineEdit)
self.sendBtn = QPushButton('发给子窗口')
self.mainLayout.addWidget(self.sendBtn)
self.sendBtn.clicked.connect(self.sendValue) # 1.将点击按钮绑定 sendValue方法
self.btn_show = QPushButton('显示子窗口')
self.btn_close = QPushButton('关闭子窗口')
self.btn_hide = QPushButton('隐藏子窗口')
self.btn_show.clicked.connect(self.openSubwindow)
self.btn_close.clicked.connect(self.closeSubwindow)
self.btn_hide.clicked.connect(self.hideSubwindow)
self.mainLayout.addWidget(self.btn_hide)
self.mainLayout.addWidget(self.btn_close)
self.mainLayout.addWidget(self.btn_show)
self.setLayout(self.mainLayout)
self.bind()
def bind(self):
self.subwindow = Subwindow()
self.subwindow.show()
self.sendValueSignal.connect(self.subwindow.sublineedit.setText) # 3.信号发生后执行绑定的方法
def sendValue(self):
message = self.IPLineEdit.text()
self.sendValueSignal.emit(message) # 2.sendValue 方法执行后触发信号发送,并且带一个参数
def openSubwindow(self):
self.subwindow.show()
def closeSubwindow(self):
self.subwindow.close()
def hideSubwindow(self):
self.subwindow.hide()
class Subwindow(QWidget):
def __init__(self):
super().__init__()
self.mainLayout = QVBoxLayout()
self.label = QLabel("子窗口")
self.sublineedit = QLineEdit()
self.mainLayout.addWidget(self.label)
self.mainLayout.addWidget(self.sublineedit)
self.setLayout(self.mainLayout)
if __name__ == '__main__':
app = QApplication([])
window = Mywindow()
window.show()
app.exec()
效果