如何在QLineEDIT中像这样制作一个额外的图标? [英] How to make an extra icon in QLineEdit like this?

查看:21
本文介绍了如何在QLineEDIT中像这样制作一个额外的图标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Qt Creator中实现一个类似以下屏幕截图的"清理"按钮,该按钮驻留在QLineEdit中,而不是单个小部件

我应该从哪里开始?

推荐答案

有关建议的解决方案,请参阅此博客文章: 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内置方法setClearButtonEnabled

这篇关于如何在QLineEDIT中像这样制作一个额外的图标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆