答案 0 :(得分:4)
您必须启用clearButtonEnabled
的{{1}}属性:
QLineEdit
您必须创建一个自定义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();
}
#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"