2

I would like to implemented a "clean" button like the following screenshot in Qt Creator, the button dwells in QLineEdit, not a single widget

enter image description here

Where should I start from ?

daisy
  • 22,498
  • 29
  • 129
  • 265

1 Answers1

6

See this blog entry for a proposed solution: Lineedit with a clear button.


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.

Laurel
  • 5,965
  • 14
  • 31
  • 57
hank
  • 9,553
  • 3
  • 35
  • 50
  • Please don't post an answer consisting only of a link, instead include the solution in your answer. This policy is defends against cases like this one, where webpage you link to has changed and no longer has a solution to this question. – nandhp May 30 '15 at 00:07