PyQt_信号与槽_两个窗口类之间信号传递

主旨

在写界面时需要主窗口与子窗口之间进行信号传递,以实现在子窗口进行相应操作(如按钮操作),主窗口可以接收信号并进行相应动作

实现方式 1

从QObejct生成的对象可以发送信号。所以可以创建一个信号,并且成为外部类showMsgBox的属性,通过窗口类调用showMsgBox实现在子窗口中信号的发送,并在主窗口中定义信号的响应函数(槽函数)

from PyQt5 import QtCore, QtGui, QtWidgets

from PyQt5.QtWidgets import QMessageBox

from PyQt5.QtCore import pyqtSignal, QObject

from main import Ui_MainWindow

from scan import Ui_Form

import sys

class scan(QtWidgets.QWidget,Ui_Form):

def __init__(self):

super(scan,self).__init__()

self.setupUi(self)

self.signal1=showMsgBox()

def getinput(self):

self.signal1.closeApp.emit("helloworld")

class showMsgBox(QObject):

closeApp=pyqtSignal(str)

class mainwindow(QtWidgets.QMainWindow,Ui_MainWindow):

def __init__(self):

super(mainwindow,self).__init__()

self.setupUi(self)

self.scanwin=scan()

self.mysignal=showMsgBox()

self.scanwin.signal1.closeApp.connect(self.haha)

def scan(self):

def haha(self,str):

text=QMessageBox.information(self,"info",str,QMessageBox.Yes | QMessageBox.No)

def dialog(self):

pass

if __name__ == '__main__':

app = QtWidgets.QApplication(sys.argv)

window = mainwindow();

window.show()

sys.exit(app.exec_())

实现方式 2

与实现方式1 原理相同,较高级写法,使用了python的神器,即装饰器,也是最常用的方法

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'main.ui'

#

# Created by: PyQt5 UI code generator 5.10.1

#

# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

from PyQt5.QtWidgets import QMessageBox

from PyQt5.QtCore import pyqtSlot, QObject, pyqtSignal

from main import Ui_MainWindow

from scan import Ui_Form

import sys

class scan(QtWidgets.QWidget,Ui_Form):

Signal_closeApp= pyqtSignal(str)#在构造函数前定义,str为传递参数的类型

def __init__(self):

super(scan,self).__init__()

self.setupUi(self)

@pyqtSlot()#当按钮按下 ,getinput 函数运行,发送Signal_closeApp信号

def getinput(self):

self.Signal_closeApp.emit("helloworld")

self.close()

class mainwindow(QtWidgets.QMainWindow,Ui_MainWindow):

def __init__(self):

super(mainwindow,self).__init__()

self.setupUi(self)

self.scanwin=scan()

self.scanwin.Signal_closeApp.connect(self.haha)#将信号与槽链接

def scan(self):

@pyqtSlot(str)#传递参数为str类型

def haha(self,str):

text=QMessageBox.information(self,"info",str,QMessageBox.Yes | QMessageBox.No)

def dialog(self):

pass

if __name__ == '__main__':

app = QtWidgets.QApplication(sys.argv)

window = mainwindow();

window.show()

sys.exit(app.exec_())

自定义信号使用方法

自定义信号在构造函数init()前定义

在子对话框定义发射信号

在主窗口定义槽函数

在主窗口连接信号和槽

参考资料

PyQt信号与槽两个类之间信号传递和槽函数执行(https://gitee.com/azhengzz/codes/k7xj4qgpy1dlfb3us62ei37)

PyQt5-基础(https://blog.csdn.net/linux_hacher/article/details/78932208)

  • 发表于:
  • 原文链接http://kuaibao.qq.com/s/20180406G0BEOZ00?refer=cp_1026
  • 腾讯「云+社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。

扫码关注云+社区

领取腾讯云代金券