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
2
3
4
5
from PyQt4.uic import loadUiType 

qtCreatorFile = "MyWindow.ui"

Ui_MainWindow, QtBaseClass = loadUiType(qtCreatorFile)

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
2
3
def focusInEvent(self, event):
self.setText("www")
self.selectAll()

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
2
txt_demo = QtGui.QLineEdit()
txt_demo.mousePressEvent = lambda _ : txt_demo.selectAll()

Assigning a lambda replaces the instance method without touching the class—lightweight and effective.

References:

  1. 使用Designer编写PyQt程序的简单流程
  2. Pyside - Select all text when QLineEdit gets focus