/**************************************************************************** ** ** Copyright (c) 2007 Trolltech ASA ** ** Use, modification and distribution is allowed without limitation, ** warranty, liability or support of any kind. ** ****************************************************************************/ #include "searchlineedit.h" #include #include #include #include SearchLineEdit::SearchLineEdit(QWidget *parent) : QLineEdit(parent) { clearButton = new QToolButton(this); QPixmap pixmap = QPixmap(":/icons/close.png").scaledToHeight(15, Qt::SmoothTransformation); clearButton->setIcon(QIcon(pixmap)); clearButton->setIconSize(pixmap.size()); clearButton->setCursor(Qt::ArrowCursor); clearButton->setStyleSheet("QToolButton { border: none; padding: 0px; }"); clearButton->hide(); connect(clearButton, SIGNAL(clicked()), this, SLOT(clear())); connect(this, SIGNAL(textChanged(const QString&)), this, SLOT(updateCloseButton(const QString&))); int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth); setStyleSheet(QString("QLineEdit { padding-right: %1px; } ").arg(clearButton->sizeHint().width() + frameWidth + 1)); QSize msz = minimumSizeHint(); setMinimumSize(qMax(msz.width(), clearButton->sizeHint().height() + frameWidth * 2 + 2), qMax(msz.height(), clearButton->sizeHint().height() + frameWidth * 2 + 2)); } void SearchLineEdit::resizeEvent(QResizeEvent *) { QSize sz = clearButton->sizeHint(); int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth); clearButton->move(rect().right() - frameWidth - sz.width(), (rect().bottom() + 1 - sz.height()) / 2); } void SearchLineEdit::updateCloseButton(const QString& text) { clearButton->setVisible(!text.isEmpty()); } void SearchLineEdit::paintEvent(QPaintEvent *event) { QLineEdit::paintEvent(event); if (text().isEmpty() && !hasFocus()) { QStyleOptionFrame option; initStyleOption(&option); QRect textRect = style()->subElementRect(QStyle::SE_LineEditContents, &option, this); QPainter painter(this); painter.setPen(Qt::gray); painter.drawText(textRect.adjusted(10, 0, 0, 0), Qt::AlignLeft | Qt::AlignVCenter, tr("Search")); } }