簡體   English   中英

如何在PyQt4中將變量從一個類訪問到另一個類?

[英]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()

輸入字段未構建。

所以

  1. 您要么要創建一個新窗口,要么必須將self.entry放在構造函數上
  2. 您要在調用openDialog之后使用現有窗口訪問其entry

編輯:

也許在這里

class Dialog(QtGui.QDialog):
    def __init__(self, parent=Window):
        super().__init__()

您正在初始化該類錯誤。 父構造函數也應使用parent = Window來調用。 然后從對話框內部,您可以通過執行self.parent來引用窗口

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM