Search code examples
pythonpython-2.7pyqtpyqt4qlineedit

puqt4 clearing the line edit field


I am trying to create tqo line edit and when i click on the line edit box i should be able to clear the current text.

I tried the below code but no success ,

Can someone point out what is wrong here?

OPTIONS = ['Enter IP Address','Number of iteration']

def __init__(self, parent=None):
    QtGui.QWidget.__init__(self, 'Details', parent=parent)
    self.options = {}
    for option in OptionBox.OPTIONS:
        self.options[option] = (QtGui.QLineEdit(option))
        self.connect(self.options[option],  QtCore.SIGNAL("clicked()"), self.clicked)
    self._gridOptions()

def clicked(self):
    QLineEdit.clear()

Solution

  • You need to use an event filter on the QLineEdit to catch the click event in it (https://qt-project.org/doc/qt-5.1/qtcore/qobject.html#eventFilter). Here is an example on how the code should look like:

    def __init__(self, parent=None):
      QtGui.QWidget.__init__(self, 'Details', parent=parent)
      self.options = {}
      for option in OptionBox.OPTIONS:
        self.options[option] = QtGui.QLineEdit(option)
        self.options[option].installEventFilter(self)
      self._gridOptions()
    
    def eventFilter(self, object, event):
      if (object in self.options.values()) and (event.type() == QtCore.QEvent.MouseButtonPress):
        object.clear()
        return False # lets the event continue to the edit
      return False
    

    Edit: from what I understand, you just want a default text to appear in the QLineEdit which describe their role. This is a good opportunity to use the placeholderText. Here is the code modified to use it (there is no more need of the eventFilter method):

    def __init__(self, parent=None):
      QtGui.QWidget.__init__(self, 'Details', parent=parent)
      self.options = {}
      for option in OptionBox.OPTIONS:
        self.options[option] = QtGui.QLineEdit()
        self.options[option].setPlaceholderText(option)
      self._gridOptions()