python logo

pyqt5 text box


Python hosting: Host, run, and code Python in the cloud!

In this comprehensive guide, discover how to leverage a textbox widget in PyQt5. This essential widget, named QLineEdit, offers methods such as setText() for setting the textbox’s value and text() to retrieve the value.

By harnessing the resize(width,height) method, the dimensions of the textbox can be easily adjusted. Meanwhile, its position can be defined using the move(x,y) method or by employing a grid layout.

Related Course:

Creating a PyQt5 Textbox:
Constructing a textbox in PyQt5 is a breeze. Below is a snippet showcasing the creation process:

self.textbox = QLineEdit(self)
self.textbox.move(20, 20)
self.textbox.resize(280,40)

PyQt5 QLineEdit Textbox

An Example of PyQt5 Textbox Implementation:
The ensuing example illustrates a window that houses a textbox. It’s pivotal to note that widgets, which can exhibit media such as images, are components of qwidget.

import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QPushButton, QAction, QLineEdit, QMessageBox
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QMainWindow):

def __init__(self):
super().__init__()
self.title = 'PyQt5 textbox - pythonspot.com'
self.left = 10
self.top = 10
self.width = 400
self.height = 140
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

# Create textbox
self.textbox = QLineEdit(self)
self.textbox.move(20, 20)
self.textbox.resize(280,40)

# Create a button in the window
self.button = QPushButton('Show text', self)
self.button.move(20,80)

# connect button to function on_click
self.button.clicked.connect(self.on_click)
self.show()

@pyqtSlot()
def on_click(self):
textboxValue = self.textbox.text()
QMessageBox.question(self, 'Message - pythonspot.com', "You typed: " + textboxValue, QMessageBox.Ok, QMessageBox.Ok)
self.textbox.setText("")

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

Looking to delve deeper? Download the extensive PyQt Code Collection here.

Navigate the tutorials: < Previous | Next >






Leave a Reply: