如何在 ComboBox 的编辑字段中创建一个按钮?

How to create a button in editing field of ComboBox?

要求是当我们在 ComboBox 中输入内容时,该字段的右侧会出现一个 X 按钮(以删除我们输入的内容)。我该怎么做?

setClearButtonEnabled

的结果

您必须启用 QLineEditclearButtonEnabled 属性:

#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();
}