First I’ll show the code.
class XLineEdit(QtGui.QLineEdit):
'''QLineEdit with clear button, which appears when user enters text.'''
def __init__(self, pixmap, parent=None):
QtGui.QLineEdit.__init__(self, parent)
self.layout = QtGui.QHBoxLayout(self)
self.image = QtGui.QLabel(self)
self.image.setCursor(QtCore.Qt.ArrowCursor)
self.image.setFocusPolicy(QtCore.Qt.NoFocus)
self.image.setStyleSheet("border: none;")
self.image.setPixmap(pixmap)
self.image.setSizePolicy(
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
self.image.adjustSize()
self.image.setScaledContents(True)
self.layout.addWidget(
self.image, alignment=QtCore.Qt.AlignRight)
self.textChanged.connect(self.changed)
self.image.hide()
def changed(self, text):
if len(text) > 0:
self.image.show()
else: # if entry is empty
self.image.hide()
That creates QLineEdit object with custom button from QLabel at the right side of QLineEdit. I have only two problems:
-
If I change the font of XLineEdit (“XLineEdit object”.setFont(QFont)), image button will look good by vertical, but will look ugly by horizontal. It seems that vertical size changes on changing the size of QLineEdit’s font, but horizontal size is not. How can I fix this? Is there any other way to create QLineEdit with clear button? I’ve tried to create QPushButton with custom QIcon, but icon doesn’t change it’s size at all (neither vertical, nor horizontal).
-
How can I create a new signal when user clicks on QLabel? It seems that there is no analog for QPushButton’s ‘clicked’.
Thanks!
While @reclosedev already commented on your question with a link to a C++ example for the clear button aspect, I wanted to add information about your second question…
You can create a clickable QLabel by overloading the MousePressEvent and emitting your own custom signal.
from PyQt4.QtCore import pyqtSignal
from PyQt4.QtGui import QLabel, QStyle
A comment about the C++ link that was provided in the other comment. Instead of using an HBoxLayout, they are just directly parenting the button to the QLabel widget, and using the resizeEvent to always move it to the right side of the QLabel.