[英]How to access variables from one class to another class in PyQt4?
我想從主窗口中獲取一個字符串,以在單擊觸發的窗口中使用。 我知道如何通過將所有語句放入單個類中來執行此操作,但是現在我正在嘗試對每個窗口一個類執行相同的操作。 這是代碼:
import sys
from PyQt4 import QtGui
class Window(QtGui.QWidget):
def __init__(self, parent=None):
super().__init__()
self.initUI()
def initUI(self):
self.value = QtGui.QLineEdit('23')
self.button = QtGui.QPushButton('Open Dialog')
self.button.clicked.connect(self.openDialog)
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.value)
vbox.addWidget(self.button)
self.setLayout(vbox)
def openDialog(self):
self.entry = self.value.text()
print(self.entry)
Dialog().exec_()
class Dialog(QtGui.QDialog):
def __init__(self, parent=Window):
super().__init__()
win = Window()
self.text = win.entry
self.label = QtGui.QLabel(self.text)
hbox = QtGui.QHBoxLayout()
hbox.addWidget(self.label)
self.setLayout(hbox)
def main():
app = QtGui.QApplication(sys.argv)
w = Window()
w.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
但是我收到錯誤“ AttributeError:'Window'對象沒有屬性'entry' “,我不知道有其他方法可以嘗試修復它。 有人可以幫我嗎?
在openDialog
方法中創建Dialog
的實例,以便您可以直接訪問其屬性。 這樣,這兩個類可以更加獨立地運行,並且您無需從Dialog
類中訪問Window
類:
def openDialog(self):
dialog = Dialog(self)
dialog.label.setText(self.value.text())
dialog.exec_()
print(dialog.label.text())
class Dialog(QtGui.QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.label = QtGui.QLabel(self)
hbox = QtGui.QHBoxLayout()
hbox.addWidget(self.label)
self.setLayout(hbox)
這里
win = Window()
self.text = win.entry
您在窗口類中聲明一個新窗口並訪問其entry
字段
class Window(QtGui.QWidget):
def __init__(self, parent=None):
super().__init__()
self.initUI()
輸入字段未構建。
所以
entry
編輯:
也許在這里
class Dialog(QtGui.QDialog):
def __init__(self, parent=Window):
super().__init__()
您正在初始化該類錯誤。 父構造函數也應使用parent = Window來調用。 然后從對話框內部,您可以通過執行self.parent
來引用窗口
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.