PySide6 自定义信号 (学习笔记)

个人理解:

如果你想要实现 窗口之间的数据传递,【这里仅是个人理解的将两个窗口定义为发送方和接收方】,以下是自定义的步骤:
1、在发送方中定义一个信号  也就是使用QtCore.Signal创建一个实例 
实例里的参数 是你所需要发送数据的数据类型,你需要发送几个数据,那么就写几个类型
例如下面代码中,我需要发送账号和密码的文本字符串到另外一个窗口,那么我定义的信号就是Signal(str,str)
2、设置信号的槽,也就是信号发送到哪里
 所以你需要在接收端 创建一个方法用来执行信号触发的操作,并且注意接收方的方法的参数 与 发送方的参数数量一致【就是萝卜坑 发多少 收多少】
 
3、触发信号
现在的情况是,我们要讲发送方的数据 发给接收端。那么在发送方或者发送方的数据,很容易。就是self.xxxx获取。然后讲获取到的数据通过变量存储下来,再用 信号.emit(参数,参数...) 发出去 

以上是自定义信号的个人理解。 至于通过什么方式触发信号,换句话说就是,你想在什么时候把一个窗口的数据 发送到 另外一个窗口 entirely up to you .通过点击按钮 然后 按钮定义一个槽 ,每次点击的时候 就通过信号.emit() 发送出去 都可以。

如果理解有错误的话,欢迎指正和讨论。

from PySide6.QtWidgets import QApplication,QWidget,QLineEdit,QLabel,QVBoxLayout,QHBoxLayout,QPushButton
from PySide6.QtCore import Signal

class SubWindow(QWidget): # 发送方
    sendData_ = Signal(str,str) # 定义信号

    # 构造函数的话就要加一个参数 来接收
    def __init__(self,parent=None):
        super().__init__()
        self.move(300,300)
        self.setWindowTitle("子窗口传送")
        # 获取父类
        self.parent = parent
        self.lbAccount = QLabel("账号")
        self.lbPassword = QLabel("密码")
        self.leAccount = QLineEdit()
        self.lePassword = QLineEdit()

        self.btn = QPushButton("登录")

        self.accountLayout = QHBoxLayout()
        self.passwordLayout = QHBoxLayout()

        self.accountLayout.addWidget(self.lbAccount)
        self.accountLayout.addWidget(self.leAccount)

        self.passwordLayout.addWidget(self.lbPassword)
        self.passwordLayout.addWidget(self.lePassword)

        self.mainLayout = QVBoxLayout()
        self.mainLayout.addLayout(self.accountLayout)
        self.mainLayout.addLayout(self.passwordLayout)
        self.mainLayout.addWidget(self.btn)
        self.setLayout(self.mainLayout)

        
        self.sendData_.connect(self.parent.getData) # 指定数据要传到哪里去的  
        self.btn.clicked.connect(self.sendData)


    def sendData(self):
        account = self.leAccount.text()
        password = self.lePassword.text()
        self.sendData_.emit(account,password) # 发送数据
        self.close()





class ParentWindow(QWidget): # 接收方
    def  __init__(self):
        super().__init__()
        self.resize(200,100)
        self.lbAccountParent = QLabel("账号")
        self.lbPasswordParent = QLabel("密码")
        self.mainLayout = QVBoxLayout()
        self.mainLayout.addWidget(self.lbAccountParent)
        self.mainLayout.addWidget(self.lbPasswordParent)
        self.setLayout(self.mainLayout)
        self.bind()

    def bind(self):
        self.subWindow = SubWindow(self) # 将父类实例传给子窗口
        self.subWindow.show()

    def getData(self,account,password): # 接收数据
        # 然后数据就可以随你处理
        self.lbAccountParent.setText(account) 
        self.lbPasswordParent.setText(password)



if __name__ == '__main__':
    app = QApplication([])
    window = ParentWindow()
    window.show()
    app.exec()

 

posted @ 2024-02-14 23:57  theGenius  阅读(959)  评论(0)    收藏  举报