How to make an extra icon in QLineEdit like this?

前端 未结 1 1719
走了就别回头了
走了就别回头了 2021-01-15 03:34

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

相关标签:
1条回答
  • 2021-01-15 04:08

    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

    0 讨论(0)
提交回复
热议问题