两个独立QWidget之间的通信
问题描述:
有两个独立的QT Designer UI格式。两个按钮都有。当点击form1中的按钮时,form2打开。点击form2中的按钮时如何向form1发送消息。一切正常,但消息。两个独立QWidget之间的通信
form1.py
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import form2 #Import for Signal
from form2 import * # Import for UI
RegForm = "regform.ui"
Ui_RegForm, QtBaseClass = uic.loadUiType(RegForm)
class RegForm(QtGui.QMainWindow, Ui_RegForm):
def __init__(self,parent = None):
super(RegForm,self).__init__(parent,flags = Qt.WindowCloseButtonHint)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.setupUi(self)
self.unHideBtn.clicked.connect(self.showUnhideForm)
self.myForm = form2.UnhideForm(self) #For Signal
self.myForm.mySignal.connect(self.receiveSignal) #Signal
def receiveSignal(self, message):
QtGui.QMessageBox.information(self, 'Message', message)
def showUnhideForm(self):
sub = UnhideForm(self)
sub.show()
form2.py
from PyQt4 import QtCore, QtGui, uic
from PyQt4.QtGui import *
from PyQt4.QtCore import *
UnhideForm = "unhide.ui"
Ui_UnhideForm, QtBaseClass = uic.loadUiType(UnhideForm)
class UnhideForm(QtGui.QMainWindow, Ui_UnhideForm):
mySignal = QtCore.pyqtSignal(str)#Signal
def __init__(self,parent = None):
super(UnhideForm,self).__init__(parent,flags = Qt.WindowCloseButtonHint)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.setupUi(self)
# On clicking emit a signal
self.quitBtn.clicked.connect(self.emitSignal)
# And Close the form
self.quitBtn.clicked.connect(self.close)
def emitSignal(self):
if(not self.signalsBlocked()):
self.mySignal.emit("Yes")
窗体2正常打开,当quitBtn被cliked关闭。但是没有消息被发送回Form1。我是PyQt的新手。请帮忙。谢谢。
答
#This is the example code for sent a message to one UI to another UI
#If your are not expecting this answer, sorry.
#Thanks, Subin
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
class FORM1 (QtGui.QWidget):
def __init__(self, parent=None):
super(FORM1, self).__init__(parent)
self.button1 = QtGui.QPushButton (self)
self.button1.setGeometry (QtCore.QRect(10, 10, 100, 30))
self.button1.setObjectName ('button1')
self.button1.setText ('Button1')
self.textEdit = QtGui.QTextEdit(self)
self.textEdit.setGeometry (QtCore.QRect(10, 50, 400, 100))
self.textEdit.setObjectName('textEdit')
self.resize(500, 200)
self.button1.clicked.connect (self.callForm2)
def callForm2 (self) :
self.form2_widget = FORM2()
self.form2_widget.show ()
self.form2_widget.button2.clicked.connect (self.sendMessage)
def sendMessage (self) :
self.textEdit.setText ('There are two separate QT Designer ui forms.Both have two buttons.')
class FORM2 (QtGui.QWidget) :
def __init__(self, parent=None):
super(FORM2, self).__init__(parent)
self.button2 = QtGui.QPushButton (self)
self.button2.setGeometry(QtCore.QRect(50, 50, 100, 30))
self.button2.setObjectName ('Button2')
self.button2.setText ('Button2')
self.resize(400, 100)
if __name__=='__main__':
app = QtGui.QApplication(sys.argv)
widget = FORM1()
widget.show()
app.exec_()
哇,它的工作原理。谢谢苏宾。非常感谢您 –
如果这解决了您的问题,我们鼓励您接受答案。我希望对所做的回答做一点解释。 – mdurant