Необходимо включить свойство clearButtonEnabled
QLineEdit
:
#include <QtWidgets>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QComboBox combo;
combo.setEditable(true);
if(QLineEdit *le = combo.lineEdit())
le->setClearButtonEnabled(true);
combo.show();
return a.exec();
}
Обновление:
Необходимо создать пользовательский QLineEdit.
#include <QtWidgets>
class LineEdit: public QLineEdit
{
Q_OBJECT
public:
LineEdit(QWidget *parent=nullptr):
QLineEdit(parent)
{
QAction *action = addAction(QIcon(":/clear.png"), QLineEdit::TrailingPosition);
button = qobject_cast<QToolButton *>(action->associatedWidgets().last());
button->hide();
connect(this, &QLineEdit::textChanged, this, &LineEdit::onTextChanged);
connect(button, &QToolButton::clicked, this, &QLineEdit::clear);
}
private slots:
void onTextChanged(const QString & text){
button->setVisible(!text.isEmpty());
}
private:
QToolButton *button;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QComboBox combo;
combo.setEditable(true);
combo.setLineEdit(new LineEdit);
combo.show();
return a.exec();
}
#include "main.moc"
Другой вариант: пользовательский стиль
#include <QtWidgets>
class ClearLineEditStyle: public QProxyStyle{
public:
using QProxyStyle::QProxyStyle;
QPixmap standardPixmap(StandardPixmap standardIcon, const QStyleOption *option, const QWidget *widget) const{
if(standardIcon == SP_LineEditClearButton){
return QPixmap(":/clear.png");
}
return QProxyStyle::standardPixmap(standardIcon, option, widget);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QComboBox combo;
ClearLineEditStyle *style = new ClearLineEditStyle(combo.style());
combo.setStyle(style);
combo.setEditable(true);
if(QLineEdit *le = combo.lineEdit())
le->setClearButtonEnabled(true);
combo.show();
return a.exec();
}