简体   繁体   English

在QLineEdit小部件上调用.text()时PYQT5崩溃

[英]PYQT5 crashing when calling .text() on a QLineEdit widget

When I run the code below my program crashes, and I believe this is to-do with the .text() called when the Line edit has something typed in it. 当我在下面的代码中运行代码时,程序崩溃,并且我相信这与在Line编辑中键入某些内容时调用.text()来完成。 I need to assign a variable to what is entered here. 我需要为此处输入的内容分配一个变量。

import sys
from PyQt5.QtWidgets import *
from PyQt5 import QtWidgets

class loginScreen(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        usernameBox = QtWidgets.QLineEdit()
        usernameBox.textChanged.connect(self.myfunc)

        vArrangement = QtWidgets.QVBoxLayout()
        vArrangement.addWidget(usernameBox)
        self.setLayout(vArrangement)

        self.show()

    def myfunc(self):
        x = usernameBox.text()
        print(x)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = loginScreen()
    sys.exit(app.exec_())

If you observe usernameBox it is created as a local variable so it can not be accessed by the other methods of the class, in your case there are 2 solutions: 如果您观察到usernameBox则将其创建为局部变量,因此该类的其他方法无法访问它,在您的情况下,有两种解决方案:

  • Make a usernameBox attribute of the class. 创建该类的usernameBox属性。

class loginScreen(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.usernameBox = QtWidgets.QLineEdit()
        self.usernameBox.textChanged.connect(self.myfunc)

        vArrangement = QtWidgets.QVBoxLayout()
        vArrangement.addWidget(self.usernameBox)
        self.setLayout(vArrangement)

        self.show()

    def myfunc(self):
        x = self.usernameBox.text()
        print(x)
  • Or use sender() that obtains the object that emits the signal, in your case the QLineEdit . 或使用sender()获得发出信号的对象,在您的情况下为QLineEdit

class loginScreen(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        usernameBox = QtWidgets.QLineEdit()
        usernameBox.textChanged.connect(self.myfunc)

        vArrangement = QtWidgets.QVBoxLayout()
        vArrangement.addWidget(usernameBox)
        self.setLayout(vArrangement)

        self.show()

    def myfunc(self):
        x = self.sender().text()
        print(x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM