I would like to implemented a \"clean\" button like the following screenshot in Qt Creator, the button dwells in QLineEdit, not a single widget
See this blog entry for a proposed solution
http://blog.qt.digia.com/blog/2007/06/06/lineedit-with-a-clear-button/
Since the original link is not available anymore, I provide a new code snippet.
The main idea is to add a QToolButton
to the QLineEdit
and position it properly.
LineEdit::LineEdit(QWidget *parent)
: QLineEdit(parent)
{
int height = sizeHint().height();
int btnSize = sizeHint().height() - 5;
clearButton = new QToolButton(this);
QPixmap pixmap(":clear.png");
clearButton->setIcon(QIcon(pixmap));
clearButton->setCursor(Qt::ArrowCursor);
clearButton->setStyleSheet("QToolButton { border: none; padding: 2px}");
clearButton->setFixedSize(btnSize, btnSize);
clearButton->hide();
int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
setStyleSheet(QString("QLineEdit { padding-right: %1px }")
.arg(btnSize - frameWidth));
setMinimumHeight(height);
connect(clearButton, SIGNAL(clicked()), this, SLOT(clear()));
connect(this, SIGNAL(textChanged(const QString&)),
this, SLOT(updateCloseButton(const QString&)));
}
void LineEdit::resizeEvent(QResizeEvent *)
{
int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
clearButton->move(width() - clearButton->width() - frameWidth, 0);
}
void LineEdit::updateCloseButton(const QString& text)
{
clearButton->setVisible(!text.isEmpty());
}
Also, since Qt 5.2 it is possible to use the QLineEdit
built-in method setClearButtonEnabled
.
http://doc.qt.io/qt-5/qlineedit.html#clearButtonEnabled-prop