Clear QLineEdit on click event
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
layout = QGridLayout()
self.setLayout(layout)
self.lineedit = QLineEdit()
self.lineedit.returnPressed.connect(self.press)
layout.addWidget(self.lineedit, 0, 0)
def press(self):
print("Hi World")
self.lineedit.clear()
The solution is to promote QtDesigner use our custom QLineEdit where we implement the signal clicked with the help of mousePressEvent, this class will be called ClickableLineEdit and the file will be called ClickableLineEdit.py.
ClickableLineEdit.py
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QLineEdit
class ClickableLineEdit(QLineEdit):
clicked = pyqtSignal()
def mousePressEvent(self, event):
self.clicked.emit()
QLineEdit.mousePressEvent(self, event)
To promote it, the following structure will be considered:
.
├── ClickableLineEdit.py
├── main.py
├── your.ui
└── QLineEdit_test.py
Open the design with Qt Designer and right click on the QLineEdit and select Promote to ...
:
A menu will open and place the following
then press and Promote. Then we generate the code again.
Then we connect the signal to clear:
class MainWindow(QMainWindow, QLineEdit_test.Ui_QLineEdit_test):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.copy_button.clicked.connect(self.copy_and_print)
self.lineEdit.clicked.connect(self.lineEdit.clear)
def copy_and_print(self):
self.label.setText(self.lineEdit.text())
Update:
PySide2:
from PySide2 import QtCore, QtWidgets
class ClickableLineEdit(QtWidgets.QLineEdit):
clicked = QtCore.Signal()
def mousePressEvent(self, event):
super(ClickableLineEdit, self).mousePressEvent(event)
self.clicked.emit()
class App(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.lineedit = ClickableLineEdit()
self.lineedit.clicked.connect(self.lineedit.clear)
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(self.lineedit)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication.instance()
if app is None:
app = QtWidgets.QApplication(sys.argv)
ex = App()
ex.show()
sys.exit(app.exec_())