How to do - QToolButton inside the QlineEdit : Qt5

2020-02-13 02:47发布

I want to add QToolButton inside the QLineEdit.

I want to clear the text of QLineEdit control on that button click.

For example how in google image:

enter image description here

I have looked :

This StackOverflow article

But still not solved my issue.

Thanks in Advance.

2条回答
欢心
2楼-- · 2020-02-13 03:43

This behaviour is available as a direct property to QLineEdit since Qt 5.2:

https://qt-project.org/doc/qt-5/qlineedit.html#clearButtonEnabled-prop

QLineEdit *edit = new QLineEdit(this);
edit->setClearButtonEnabled(true);

You can add a custom QAction with your self-defined icons to the QLineEdit:

https://qt-project.org/doc/qt-5/qlineedit.html#addAction

QLineEdit *edit = new QLineEdit(this);
QAction *action =
    edit->addAction(QIcon("/path/to/icon"), QLineEdit::ActionPosition::LeadingPosition);
connect(action, &QAction::triggered, this, &ThisObject::doSomething);
查看更多
该账号已被封号
3楼-- · 2020-02-13 03:43

//Create QToolButton:

QToolButton *clearButton = new QToolButton(this);
QPixmap pixmap(":/new/AppResource/images/clear_button.png");
clearButton->setIcon(QIcon(pixmap));
clearButton->setIconSize(pixmap.size());
clearButton->setCursor(Qt::ArrowCursor);
clearButton->setStyleSheet("QToolButton { border: none; padding: 0px; }");
clearButton->hide();

Connect Signal-Slot:

connect(clearButton, SIGNAL(clicked()), this, SLOT(clear()));
connect(this, SIGNAL(textChanged(const QString&)), this, SLOT(updateCloseButton(const QString&)));

Visible on Text Enter into serach box:

clearButton->setVisible(true);
查看更多
登录 后发表回答