2012-07-08 20 views

回答

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

+0

請不要發表僅由鏈接組成的答案,而應在答案中包含解決方案。這項政策是針對這種情況進行辯護的,其中鏈接到的網頁已更改,並且不再有解決此問題的方法。 – nandhp 2015-05-30 00:07:58

+0

@nandhp我已經更新了答案。 – hank 2015-06-01 07:22:50