如何在QLineEdit中创建一个额外的图标?

时间:2012-07-08 08:51:38

标签: qt4

我想在Qt Creator中实现一个“干净”按钮,如下面的屏幕截图,按钮位于QLineEdit中,而不是单个小部件

enter image description here

我应该从哪里开始?

1 个答案:

答案 0 :(得分:5)

有关建议的解决方案,请参阅此博客条目 http://blog.qt.digia.com/blog/2007/06/06/lineedit-with-a-clear-button/

由于原始链接不再可用,我提供了一个新的代码段。

主要想法是向QToolButton添加QLineEdit并正确定位。

LineEdit::LineEdit(QWidget *parent)
    : QLineEdit(parent)
{
    int height = sizeHint().height();
    int btnSize = sizeHint().height() - 5;

    clearButton = new QToolButton(this);
    QPixmap pixmap(":clear.png");
    clearButton->setIcon(QIcon(pixmap));
    clearButton->setCursor(Qt::ArrowCursor);
    clearButton->setStyleSheet("QToolButton { border: none; padding: 2px}");
    clearButton->setFixedSize(btnSize, btnSize);
    clearButton->hide();

    int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
    setStyleSheet(QString("QLineEdit { padding-right: %1px }")
                                                .arg(btnSize - frameWidth));
    setMinimumHeight(height);

    connect(clearButton, SIGNAL(clicked()), this, SLOT(clear()));
    connect(this, SIGNAL(textChanged(const QString&)), 
            this, SLOT(updateCloseButton(const QString&)));
}

void LineEdit::resizeEvent(QResizeEvent *)
{
    int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
    clearButton->move(width() - clearButton->width() - frameWidth, 0);
}

void LineEdit::updateCloseButton(const QString& text)
{
    clearButton->setVisible(!text.isEmpty());
}

此外,由于Qt 5.2,可以使用QLineEdit内置方法setClearButtonEnabledhttp://doc.qt.io/qt-5/qlineedit.html#clearButtonEnabled-prop