PyQt5 textbox example
In this article you will learn how to use a textbox in PyQt5. The widget is called QLineEdit and has the methods setText() to set the textbox value and text() to get the value.
We can set the size of the textbox using the resize(width,height) method. The position can be set using the move(x,y) method or using a grid layout.
PyQt5 textbox Creation of the textbox is fairly straightforward:
self.textbox = QLineEdit(self)
self.textbox.move(20, 20)
self.textbox.resize(280,40)
PyQt5 textbox example
The example below creates a window with a textbox.
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_())
Placeholder text and password mode
You can add gray hint text inside the input box to show users what to type. Use setPlaceholderText():
self.textbox.setPlaceholderText("Enter your username...")
For password input fields where characters should be hidden with dots or asterisks, use setEchoMode():
self.textbox.setEchoMode(QLineEdit.Password)

Pressing the Enter key
You do not always need a submit button. To trigger a function when the user presses Enter inside the text box, connect the returnPressed signal:
self.textbox.returnPressed.connect(self.on_click)
Download PyQT Code (Bulk Collection)
