4

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.

Community
  • 1
  • 1
AB Bolim
  • 1,997
  • 2
  • 23
  • 47

2 Answers2

13

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);
Polem
  • 233
  • 1
  • 8
  • For python users it works like this: `action = edit.addAction(QIcon('icon.png'), QLineEdit::ActionPosition::TrailingPosition)` Then do `action.triggered.connect(func_name)` – Have a nice day May 05 '21 at 22:32
  • This is, however, not what the OP is asking for. He is asking for a QToolButton inside a QLineEdit, which makes sense. Sometimes, you may want to have a drop-down list (menu) that QToolButton offers instead of a raw icon. The clear is a slightly special case here. – László Papp May 16 '22 at 11:37
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);
AB Bolim
  • 1,997
  • 2
  • 23
  • 47
  • Yes, I do not think I have found a way to put a QToolButton inside the QLineEdit. It is like that they better go together in a horizontal layout. – László Papp May 16 '22 at 11:37