如何在不使用 PyQt 上的 findChild 的情况下访问方法内部的小部件?

How can I access widgets inside methods without using findChild on PyQt?

我是 PyQt 的新手,我正在制作一个类似应用程序的小聊天。我初始化了 GUI 并创建了几种方法来管理用户输入。问题是,我无法使用网上教程中显示的 self.Method() 指令。出于某种原因 Python 告诉我 object 没有属性 'WIDGET' WIDGET 在这种情况下是 QListWidget。

我设法使用 findChild 克服了这个问题,但我不确定这是正确的方法。从 PyQt 的方法中访问小部件的正确方法是什么?

这是我的代码:

import stuff *
class ASIMOV(QWidget):
        def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        QToolTip.setFont(QFont('SansSerif', 12))

        botLog = QListWidget(self)
        botLog.resize(150, 150)

        botInput = QLineEdit(self)
        botInput.returnPressed.connect(self.handleChatInput)

        vbox = QVBoxLayout()
        vbox.addWidget(botLog)
        vbox.addWidget(botInput)

        self.setLayout(vbox)
        self.resize(600, 400)
        self.show()

    def startChat(self, botLog):
        u = ASIMOV_user.User()
        #Greet user
        botLog.addItem('#: Hey there' + u.getName())
        botChat = ASIMOV_chat.Chat()

    def handleChatInput(self):
        u = ASIMOV_user.User()
        print(self.botLog.text())
        botInput = self.findChild(QLineEdit, "")
        botLog = self.findChild(QListWidget, "")
        #lineEdits = self.findChildren(QLineEdit)
        botLog.addItem('#' + u.getName() + ': ' + botInput.text())
        #print(botInput.text())

if __name__=="__main__":
    app = QApplication(sys.argv)
    w = ASIMOV()
    sys.exit(app.exec_())

此外,每次我想访问他们的方法(例如来自 ASIMOV_user class 的 getter 时,我必须初始化一个 class 吗?

three_pineapples给出的答案。在这种情况下,原始代码声明的小部件没有 self 运算符,这使它们成为本地元素。

正如他所描述的,它只需要添加 self.WIDGET 就可以使它们对应用程序中的其余方法可用。

原始答案在这里:

Store a reference to the widgets when you create them by making them instance attributes (eg self.botInput = QLineEdit(self)). Then you can access them in the same way (self.botInput) from any method of your class. I'd suggest running through some basic tutorials on object oriented programming with Python to become familiar with the concepts you'll need to successfully write GUI programs