I am trying to get the text variable from a QLineEdit
widget that is created in a function within a class. Usually I would specify the class in which the variable was created for ex. var = classname.variable
but this doesn't work in this case since the variable is created in a function in a class. Here is my code:
from PyQt5.QtWidgets import QWidget, QLineEdit, QApplication, QMainWindow
import sys
class main(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(0, 0, 200, 150)
line = QLineEdit(self)
line.resize(100, 21)
line.move(10, 35)
line.setText("the coolest text")
self.show()
text = main.line.text()
print(text)
if __name__ == "__main__":
app = QApplication(sys.argv)
gui = main()
sys.exit(app.exec())
How can I get this variable without putting all my code in one class?
Try it:
from PyQt5.QtWidgets import QWidget, QLineEdit, QApplication, QMainWindow
import sys
class main(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(0, 0, 270, 150)
self.line = QLineEdit(self)
self.line.resize(120, 21)
self.line.move(83, 35)
self.line.setText("the coolest text")
self.show()
# text = main.line.text()
# print(text)
if __name__ == "__main__":
app = QApplication(sys.argv) # +
gui = main()
# app = QApplication
text = gui.line.text() # +
print(text)
sys.exit(app.exec_())