How to make an extra icon in QLineEdit like this?

…衆ロ難τιáo~ 提交于 2019-12-24 00:43:07

问题


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

Where should I start from ?


回答1:


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



来源:https://stackoverflow.com/questions/11381865/how-to-make-an-extra-icon-in-qlineedit-like-this

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!