繁体   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