So I’m a noob to PyQt and to python for that matter. I’m trying to write a simple Qt app that allows you to click a button then display what you entered in the text field in the command prompt, (i know this is ridiculously basic, but I’m trying to learn it) but I can’t seem to figure out how to access the textBox attribute from printTexInput() method. so my question is how would you access that value from another method? or is my way of thinking about this completely wrong? any help would be greatly appreciated.
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
textBoxLabel = QtGui.QLabel('Text Input')
self.textBox = QtGui.QLineEdit()
okayButton = QtGui.QPushButton("Okay")
okayButton.clicked.connect(self.printTexInput)
grid = QtGui.QGridLayout()
grid.setSpacing(10)
grid.addWidget(textBoxLabel, 0, 0)
grid.addWidget(textBox, 0, 1)
grid.addWidget(okayButton, 3, 3)
self.setLayout(grid)
self.setGeometry(300,300,250,250)
self.setWindowTitle("test")
self.show()
def printTexInput(self):
print self.textBox.text()
self.close()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__=='__main__':
main()
Right now
textBoxis a local variable in theinitUImethod, and it’s lost forever when you leave that method. If you want to storetextBoxon this instance of your class, you need to sayself.textBox = QtGui.QLineEdit()instead. Then inprintTextInputyou can callprint self.textBox.text()instead.