If your input field is a QtWidget.QLineEdit
, you get the text with the call to .text()
method.
If it is a field of type QtWidgets.QTextEdit
, you first get a reference to the QTextDocument
associated, and then you can have all the content being edited with a call to .toPlainText()
method
conteudo = widget.document().toPlainText()
"hello world" type app to always display the last line entered in the edit area:
from PyQt5 import QtWidgets
import sys
def update(document, line):
text = document.toPlainText()
last_line = text.split("\n")[-1]
line.setText(last_line)
def main():
app = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QWidget()
manager = QtWidgets.QGridLayout(window)
area = QtWidgets.QTextEdit()
line = QtWidgets.QLineEdit()
document = area.document()
document.contentsChange.connect(lambda: update(document, line))
manager.addWidget(area, 0, 0)
manager.addWidget(line, 1, 0)
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
About this program: the document.contentsChange.connect(lambda: update(document, line))
line connects the text change signal with an anonymous function defined in the same place: lambda: update(document, line)
- because the Qt signals do not send other parameters together. As in callback update
I want to have access to the document and the other widget, lambda is called without parameters, and calls update
passing the variables that I want to have access to in the other function as parameters.