How to place an icon onto a QLineEdit?

后端 未结 7 917
终归单人心
终归单人心 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:28

    Here is an alternate simple way:

    Set the placeholderText to "

    0 讨论(0)
  • 2021-02-08 07:30

    QT5 addAction

    ```

    const QIcon passwordIcon(":/new/icons/res/passwd.png");
    ui->password->setClearButtonEnabled(true);
    ui->password->addAction(passwordIcon, QLineEdit::LeadingPosition);
    

    ```

    0 讨论(0)
  • 2021-02-08 07:35

    From QT 5.2 onwards you can do something like this. You should use pointers if you want to make it more flexible:

    
    QIcon *ico;
    ico = new QIcon(":/images/search.ico");
    searchEdit->addAction(*ico, QLineEdit::LeadingPosition);
    
    
    0 讨论(0)
  • 2021-02-08 07:43

    Simple Way for Dummies

    1. Add a QLineEdit, and set it frameless by QLineEdit::setFrame
    2. Add a QLabel with background color in white (by stylesheet) and a icon
    3. Combine the line edit and the label with a layout, set spacing to 0
    4. Set placeholder text with QLineEdit::setPlaceholderText

    Result

    enter image description here


    Advanced Way

    Check this thread: "Can QLineEdit do this?"

    And the related python code: http://bazaar.launchpad.net/~henning-schroeder/%2Bjunk/qtwidgets/annotate/head:/qtwidgets/lineedit.py

    Or

    "How to do - inside in QLineEdit insert the button.[pyqt4]"

    Basically customized a QLineEdit by painting a widget(label, button or even combobox) onto it. Then reset the margin, cursor, padding and the paint event. No magics!

    0 讨论(0)
  • 2021-02-08 07:45

    Here's a way to achieve this with stylesheets only:

    QLineEdit {
        background: #f3f3f3;
        background-image: url(:Images/search.svg); /* actual size, e.g. 16x16 */
        background-repeat: no-repeat;
        background-position: left;
        color: #252424;
        font-family: SegoeUI;
        font-size: 12px;
        padding: 2 2 2 20; /* left padding (last number) must be more than the icon's width */
    }
    

    Here's the result:

    It's still not perfect. You don't have much influence over the icon's position.

    0 讨论(0)
  • 2021-02-08 07:46
    QLineEdit* _lineEdit = new QLineEdit();
    _lineEdit->setClearButtonEnabled(true);
    _lineEdit->addAction(":/resources/search.ico", QLineEdit::LeadingPosition);
    _lineEdit->setPlaceHolderText("Search...");
    

    extracted from: http://saurabhg.com/programming/search-box-using-qlineedit/

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