Question

I want to add QToolButton inside the QLineEdit.

I want to clear the text of QLineEdit control on that button click.

For example how in google image:

enter image description here

I have looked :

This StackOverflow article

But still not solved my issue.

Thanks in Advance.

Was it helpful?

Solution 2

//Create QToolButton:

QToolButton *clearButton = new QToolButton(this);
QPixmap pixmap(":/new/AppResource/images/clear_button.png");
clearButton->setIcon(QIcon(pixmap));
clearButton->setIconSize(pixmap.size());
clearButton->setCursor(Qt::ArrowCursor);
clearButton->setStyleSheet("QToolButton { border: none; padding: 0px; }");
clearButton->hide();

Connect Signal-Slot:

connect(clearButton, SIGNAL(clicked()), this, SLOT(clear()));
connect(this, SIGNAL(textChanged(const QString&)), this, SLOT(updateCloseButton(const QString&)));

Visible on Text Enter into serach box:

clearButton->setVisible(true);

OTHER TIPS

This behaviour is available as a direct property to QLineEdit since Qt 5.2:

https://qt-project.org/doc/qt-5/qlineedit.html#clearButtonEnabled-prop

QLineEdit *edit = new QLineEdit(this);
edit->setClearButtonEnabled(true);

You can add a custom QAction with your self-defined icons to the QLineEdit:

https://qt-project.org/doc/qt-5/qlineedit.html#addAction

QLineEdit *edit = new QLineEdit(this);
QAction *action =
    edit->addAction(QIcon("/path/to/icon"), QLineEdit::ActionPosition::LeadingPosition);
connect(action, &QAction::triggered, this, &ThisObject::doSomething);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top