2

我想在 Qt Creator 中实现一个“干净”按钮,如下图所示,该按钮位于 QLineEdit 中,而不是单个小部件

在此处输入图像描述

我应该从哪里开始?

4

1 回答 1

6

请参阅此博客条目以获取建议的解决方案: Lineedit with a clear button


主要思想是添加 aQToolButtonQLineEdit正确定位它。

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内置方法setClearButtonEnabled

于 2012-07-09T08:41:18.930 回答