Access data from the parent window in a child wind

2020-04-20 06:12发布

问题:

I have two windows (App.py and ChildApp.py) and .ui files for both with same name.

App.py:

import sys
from PyQt4 import QtCore, QtGui, uic
from ChildApp import ChildApp
qtCreatorFile = "App.ui" # Enter file here.
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
class App(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)
        self.message = None
        self.child_window = ChildApp()
        self.pushButton.clicked.connect(self.sendMessage)
    def sendMessage(self):
        self.message = self.lineEdit.text()
        self.child_window.show()
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = App()
    window.show()
    sys.exit(app.exec_())

ChildApp.py:

import sys
from PyQt4 import QtCore, QtGui, uic
qtCreatorFile = "ChildApp.ui" # Enter file here.
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
class ChildApp(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.alertmessage)
    def alertmessage(self):
        message = "test"
        self.label.setText("Message : "+message)
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = ChildApp()
    window.show()
    sys.exit(app.exec_())

In Main.py file I have a variable self.message. When I click on the button "Do something with text", text in the textbox is assigned to self.message and the child window is opened.

Now in the child window, when I click on button "Show message", the method alertmessage() is called, where it sets message = "text". This variable message must be assigned to value of self.message from MainApp.py.

Please help

Thank you

回答1:

Call the child that way:

    self.child_window = ChildApp(parent=self)

Define the child app this way:

class ChildApp(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self, parent):
        self.parent = parent

you can use the parent variables through self.parent.whatever

It must work, but I wouldn't advise this because you are not supposed to know the fields of the parent form the child.



回答2:

I don't think you can get local data from the parent. I would do the following:

Use a signal to update the child when the text is changed in the lineEdit:

self.lineEdit.textChanged.connect(self.updateChild)

Add this function in the main window:

def updateChild(self):
    self.child_window.setMessage(self.lineEdit.text())

and keep the variable self._message updated in the child window:

def setMessage(self, message):
    self._message=message

so that whenever you need this variable, it is up to date