How to place an icon onto a QLineEdit?

后端 未结 7 922
终归单人心
终归单人心 2021-02-08 07:09

There is a Search field with the magnification-lens and a greyed out \"search\" keyword at the top right corner of stackoverflow.com web site:

相关标签:
7条回答
  • 2021-02-08 07:47

    To have a result like this:

    You can subclass the QLineEdit.
    So your header should look something like this:

    #ifndef LINEEDITICON_H
    #define LINEEDITICON_H
    
    #include <QLineEdit>
    #include <QIcon>
    
    class LineEditIcon : public QLineEdit
    {
        Q_OBJECT
    
    public:
        LineEditIcon(const QIcon icon, QWidget *parent = Q_NULLPTR);
        ~LineEditIcon();
        void setIcon(QIcon icon);    
    protected:
        virtual void paintEvent(QPaintEvent *event);    
    private:
        QIcon m_icon;       
    };
    
    #endif // LINEEDITICON_H
    

    And your source file look like:

    #include "lineediticon.h"
    #include <QPainter>
    
    LineEditIcon::LineEditIcon(const QIcon icon, QWidget *parent)
        : QLineEdit(parent)
    {
        setIcon(icon);
    }
    
    LineEditIcon::~LineEditIcon()
    {    
    }
    
    void LineEditIcon::setIcon(QIcon icon)
    {
        m_icon = icon;
        if (m_icon.isNull())
            setTextMargins(1, 1, 1, 1);
        else
            setTextMargins(20, 1, 1, 1);
    }
    
    void LineEditIcon::paintEvent(QPaintEvent * event)
    {
        QLineEdit::paintEvent(event);
        if (!m_icon.isNull()) {
            QPainter painter(this);
            QPixmap pxm = m_icon.pixmap(height() - 6, height() - 6);
            int x = 2, cx = pxm.width();
    
            painter.drawPixmap(x, 3, pxm);
            painter.setPen(QColor("lightgrey"));
            painter.drawLine(cx + 2, 3, cx + 2, height() - 4);
        }
    }
    

    Edit: A possible solution is to use a custom plugin to use it directly in QtDesigner.

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