This week, at work I had to implement a search box for a software I am working on. The search box is to filter some data dynamically as user types a query. I wanted to show a clear (cross) icon at the right side of the search box so that user can clear the results instead of selecting the current query and deleting it manually. Lastly, for clarity I wanted to show a search icon on the left side of search box. The search box looks like this:

After the user enters a query a clear icon appears on the right. The clear icon is in fact a button and clicking it will clear the current search.
It is really easy to make this search box using QLineEdit. We need only the following three lines of code:
QLineEdit* _lineEdit = new QLineEdit(); _lineEdit->setClearButtonEnabled(true); _lineEdit->addAction(":/resources/search.ico", QLineEdit::LeadingPosition); _lineEdit->setPlaceHolderText("Search..."); // add _lineEdit to your widget
Line 2 enables the clear button which adds the clear action and cross icon to the right. Line 3 adds another action with a search icon to the left of the QLineEdit. We don’t listen to this action as it is merely decorative. Line 4 adds a placeholder text which is shown in the QLineEdit but is cleared as soon as user starts typing.
We only connect textChanged(const QString&) signal which is emitted both when a user clicks on the cross icon and when he enters a search query.
how to make search box to show previously searched text in qt
This is awesomely nice done !! Thank you so much !
You are most welcome 🙂