在 PyQt 的子窗口中从父窗口访问数据 [英] Access data from the parent window in a child window in PyQt
问题描述
我有两个同名的窗口(App.py 和 ChildApp.py)和 .ui 文件.
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:
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_())
在 Main.py 文件中,我有一个变量 self.message
.当我点击Do something with text"按钮时,文本框中的文本被分配给 self.message
并打开子窗口.
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.
现在在子窗口中,当我单击显示消息"按钮时,将调用方法 alertmessage()
,它设置 message = "text"
.必须将此变量 message
分配给 MainApp.py 中的 self.message
值.
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.
请帮忙
谢谢
推荐答案
这样称呼孩子:
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
你可以通过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.
这篇关于在 PyQt 的子窗口中从父窗口访问数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!