Select All Text on Click in QLineEdit
I needed a QLineEdit
that selects all text when you click it. Since the widget has no built-in click signal, we have to handle it ourselves.
The requirement
A project of mine includes a bare-bones browser with a standard QLineEdit
as the address bar. The UI comes from Qt Designer, so I load the .ui
file directly—it keeps visual tweaks simple.
The goal is to mimic Chrome: click the address bar and the entire URL becomes selected.
Attempted solution
QLineEdit
does not emit a single-click signal. The internet suggests subclassing the widget. Because I started from a .ui
file, that means converting it to Python first:
pyuic4 -i 0 MyWindow.ui -o MyWindow.py
After compiling the UI, change the import from:
1 | from PyQt4.uic import loadUiType |
to:
1 | from MyWindow import Ui_MainWindow |
Now you can override methods on the subclass. Two candidates are mousePressEvent()
and focusInEvent()
. My first try used focusInEvent()
:
1 | def focusInEvent(self, event): |
setText()
worked, but selectAll()
did not. The reason, as someone pointed out, is that a click clears the selection immediately after focusInEvent()
runs.
Switching to mousePressEvent()
solves it.
A cleaner approach
The same answer also shared a neat trick:
1 | txt_demo = QtGui.QLineEdit() |
Assigning a lambda replaces the instance method without touching the class—lightweight and effective.
References: