怎么做 - QlineEdit里面的QToolButton:Qt5

时间:2014-04-16 07:18:32

标签: windows qt5 qlineedit qpushbutton

我想在QToolButton内添加QLineEdit

我希望清除该按钮点击的QLineEdit控制文本。

例如google图片中的内容:

enter image description here

我看过了:

StackOverflow article

但仍未解决我的问题。

先谢谢。

2 个答案:

答案 0 :(得分:8)

此行为作为QLineEdit的直接属性提供,因为Qt 5.2

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

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

您可以使用自定义图标向QLineEdit添加自定义QAction:

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);

答案 1 :(得分:2)

//创建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(clearButton, SIGNAL(clicked()), this, SLOT(clear()));
connect(this, SIGNAL(textChanged(const QString&)), this, SLOT(updateCloseButton(const QString&)));

在文本上可见进入搜索框:

clearButton->setVisible(true);