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

时间:2019-02-26 12:21:31

标签: c++ qt qt5 qcombobox

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

enter image description here

setClearButtonEnabled的结果

enter image description here

1 个答案:

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

enter image description here

另一个选择:自定义样式

#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"