I'm currently working on a program where, in a QFormLayout, I have two columns of QLineEdits. The first column I have stored in a list (meaning they are easily accessible), while the second column isn't stored in a variable or list. I'm trying to access the texts of the QLineEdits in the second column, but am always running into an error.
I currently have no intentions of using a second list/ dictionary to grant access to the second column, as using the getWidgetPosition and itemAt functions should provide an easier route for access to these values.
from PyQt5.QtWidgets import *
app = QApplication([])
window = QWidget()
layout = QFormLayout()
entry1 = QLineEdit()
layout.addRow(entry1,QLineEdit())
ePos = layout.getWidgetPosition(entry1)
text = layout.itemAt(ePos[1],ePos[0]+1).text()
print(text)
window.setLayout(layout)
window.show()
app.exec_()
The above code is just an example that's close to the code that I'm trying to use. For some reason, accessing the text of the second column of QLineEdits isn't possible as I get this error message:
Traceback (most recent call last):
File "sampleProblem.py", line 11, in <module>
text = layout.itemAt(ePos[1],ePos[0]+1).text()
AttributeError: 'QWidgetItem' object has no attribute 'text'
The itemAt()
method of the layouts returns a QLayoutItem
, the QLayoutItem
encapsulates another layout or another widget, then to get the widget (in your case QLineEdit) you must use the widget()
method, and then just get the text.
import sys
from PyQt5 import QtWidgets
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QWidget()
layout = QtWidgets.QFormLayout(window)
entry1 = QtWidgets.QLineEdit()
layout.addRow(entry1, QtWidgets.QLineEdit())
i, j = layout.getWidgetPosition(entry1)
widget_item = layout.itemAt(i, j+1)
widget = widget_item.widget()
text = widget.text()
print(text)
window.show()
sys.exit(app.exec_())