How to access textedit fields in pyqt?
TextEdit is a widget in PyQt5 that can be used to take input from the user and display the data to the user. It can take single-line text or multiline texts. A vertical scroll bar appears if the text does not fit into the widget. Here, we will create two TextEdit fields and a button. In the first TextEdit field, we will enter a number, and then on clicking the button, 10 will be added to that number and the result will be displayed in the second TextEdit field. TextEdit widget is provided by PyQt5 that can be installed in python using the following command.
Required Package:
pip install PyQt5
Implementation: Stepwise
Step 1: Let us first create the two TextEdit fields using PyQt5.
Python3
self .textEdit1 = QTextEdit()
self .textEdit2 = QTextEdit()
self .btnPress1 = QPushButton( "Button 1" )
|
Step 2: To access the number in the first TextEdit and add 10 to it, we will use the following command.
Python3
result = self .textEdit1.toPlainText() + 10
|
Step 3: To put this result in the second TextEdit, we will use the following command.
Python3
self .textEdit2.setPlainText( str (result))
|
Step 4: The above line of code will display the updated result in the second TextEdit.
Code Output
Code Implementation
Here, we are importing PyQt and creating a class TextEditDemo in which we are setting the size of a window and creating the two TextEdit boxes one is for taking an input and another is for showing a result after you click on a button. The result will be always adding 10 to the input number.
Python
from PyQt5.QtWidgets import QApplication, QWidget,\
QTextEdit, QVBoxLayout, QPushButton
import sys
class TextEditDemo(QWidget):
def __init__( self , parent = None ):
super ().__init__(parent)
self .setWindowTitle( "QTextEdit" )
self .resize( 300 , 270 )
self .textEdit1 = QTextEdit()
self .textEdit2 = QTextEdit()
self .btnPress1 = QPushButton( "Button 1" )
layout = QVBoxLayout()
layout.addWidget( self .textEdit1)
layout.addWidget( self .textEdit2)
layout.addWidget( self .btnPress1)
self .setLayout(layout)
self .btnPress1.clicked.connect( self .btnPress1_Clicked)
def btnPress1_Clicked( self ):
result = int ( self .textEdit1.toPlainText()) + \
10
self .textEdit2.setPlainText( str (result))
if __name__ = = '__main__' :
app = QApplication(sys.argv)
win = TextEditDemo()
win.show()
sys.exit(app.exec_())
|
Output:
GIF showing the output
Last Updated :
05 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...