現在的原始博客文章了,但Trolltech once posted an example of a clear button Qt的4
結果
線編輯與無文字:
線編輯與一些文字(出現按鈕):
線編輯全文(不走按鈕下方):
來源
lineedit.h
/****************************************************************************
**
** Copyright (c) 2007 Trolltech ASA <[email protected]>
**
** Use, modification and distribution is allowed without limitation,
** warranty, liability or support of any kind.
**
****************************************************************************/
#ifndef LINEEDIT_H
#define LINEEDIT_H
#include <QLineEdit>
class QToolButton;
class LineEdit : public QLineEdit
{
Q_OBJECT
public:
LineEdit(QWidget *parent = 0);
protected:
void resizeEvent(QResizeEvent *);
private slots:
void updateCloseButton(const QString &text);
private:
QToolButton *clearButton;
};
#endif // LIENEDIT_H
lineedit.cpp
/****************************************************************************
**
** Copyright (c) 2007 Trolltech ASA <[email protected]>
**
** Use, modification and distribution is allowed without limitation,
** warranty, liability or support of any kind.
**
****************************************************************************/
#include "lineedit.h"
#include <QToolButton>
#include <QStyle>
LineEdit::LineEdit(QWidget *parent)
: QLineEdit(parent)
{
clearButton = new QToolButton(this);
QPixmap pixmap("fileclose.png");
clearButton->setIcon(QIcon(pixmap));
clearButton->setIconSize(pixmap.size());
clearButton->setCursor(Qt::ArrowCursor);
clearButton->setStyleSheet("QToolButton { border: none; padding: 0px; }");
clearButton->hide();
connect(clearButton, SIGNAL(clicked()), this, SLOT(clear()));
connect(this, SIGNAL(textChanged(const QString&)), this, SLOT(updateCloseButton(const QString&)));
int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
setStyleSheet(QString("QLineEdit { padding-right: %1px; } ").arg(clearButton->sizeHint().width() + frameWidth + 1));
QSize msz = minimumSizeHint();
setMinimumSize(qMax(msz.width(), clearButton->sizeHint().height() + frameWidth * 2 + 2),
qMax(msz.height(), clearButton->sizeHint().height() + frameWidth * 2 + 2));
}
void LineEdit::resizeEvent(QResizeEvent *)
{
QSize sz = clearButton->sizeHint();
int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
clearButton->move(rect().right() - frameWidth - sz.width(),
(rect().bottom() + 1 - sz.height())/2);
}
void LineEdit::updateCloseButton(const QString& text)
{
clearButton->setVisible(!text.isEmpty());
}
你想在你的QLineEdit的中添加多個QToolButton? –
現在我只需要添加一個,但將來可能會增加兩個或更多 – ArmanHunanyan
我在下面發佈了我的解決方案。那裏使用ResizeEvent。你也可以使用QSS來設計QLineEdit,所以我認爲它就足夠了。 –