qt4 - 如何在 QLineEdit 中制作一个额外的图标?

标签 qt4

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

enter image description here

我应该从哪里开始?

最佳答案

有关建议的解决方案,请参阅此博客条目: Lineedit with a clear button .


主要思路是在QLineEdit中添加一个QToolButton,并适当定位。

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 .

关于qt4 - 如何在 QLineEdit 中制作一个额外的图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11381865/

相关文章:

python - QTreeWidget双击展开动画

layout - Qt4:隐藏次要小部件,同时保持中央小部件的大小

c++ - 在 QDialog 表单之间传递 QString 变量

c++ - 如何禁用 QToolbar 上的工具提示?

c++ - 如何在 Qt 中安装自定义小部件?

qt - 减少表格 View 的单元格填充或边距

c++ - QtConcurrent::run 异常通知

c++ - 在 Qt Eventloop 启动之前,我的代码如何接收信号

c++ - 使用 qSort 时遇到问题

java - 如何混合 C++ Qt 对象和 Qt Jambi 对象