[Solved] PyQt4 - Passing data between widget instances
-
I can't seem to figure out how to do this. I'd like to create a mainWidget that handles instances of several other widgets where the user can interact with one instance and the other instances will recognize their interaction.
The code below is an operational example where it prints the users interaction instead of passing the values back to either the mainWidget (that's where I'm stuck). mainWidget creates WidgetA and a pushButton. On click widgetB is created (lineEdit & PushBtn), on click of widgetB pushbutton I'd like data in line edit to replace text of existing instance WidgetA (self.editor).
@import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *class mainWidget(QWidget):
def init(self,parent):
super(mainWidget, self).init(parent)'''Widget A''' self.editor = WidgetA(self) self.Btn = QPushButton('input button', self) mainLayout = QVBoxLayout() mainLayout.addWidget(self.Btn) mainLayout.addWidget(self.editor) self.setLayout(mainLayout) #signals self.connect(self.Btn, SIGNAL("clicked()"),self.BtnClick) def BtnClick(self): #on self.Btn Click create: '''Widget B''' self.inputDlg = WidgetB(self) self.inputDlg.show() #Tried a setText function here that would change self.Editor Text by #referencing a global variable but that did not work either
class WidgetA(QTextEdit):
def init(self, parent):
super(WidgetA, self).init(parent)
self.setPlainText("Starting Text")class WidgetB(QDialog):
def init(self, parent):
super(WidgetB, self).init(parent)self.inputBox = QLineEdit(self) self.ok = QPushButton('input button', self) mainLayout = QVBoxLayout() mainLayout.addWidget(self.ok) mainLayout.addWidget(self.inputBox) self.setLayout(mainLayout) self.setLayout(mainLayout) #signals self.connect(self.ok, SIGNAL("clicked()"),self.changeWidgetAText) def changeWidgetAText(self): #Would like this signal to cahnge widgetA's text instance "editor print("Would like widget A instance self.editor to read '%s'" % (self.inputBox.text())) self.close()
if name == "main":
app = QApplication(sys.argv)
form = mainWidget(None)
form.show()
app.exec_()@ -
the solution is:
@ def BtnClick(self):
#on self.Btn Click create:
'''Widget B'''
inputDlg = WidgetB(self)
inputDlg.show()
if inputDlg.exec_():
self.editor.acceptUserInput(inputDlg.userInput())@userInput being a getter in WidgetB
acceptUserInput being a setter in WidgetAOther possible solution would be using global variable but you still need .exec_() to make it work.