puqt4清除行编辑字段

时间:2013-07-22 06:45:59

标签: python python-2.7 pyqt pyqt4 qlineedit

我正在尝试创建tqo行编辑,当我点击行编辑框时,我应该能够清除当前文本。

我尝试了以下代码,但没有成功,

有人可以指出这里有什么问题吗?

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()

1 个答案:

答案 0 :(得分:1)

您需要在QLineEdit上使用事件过滤器来捕获其中的click事件(https://qt-project.org/doc/qt-5.1/qtcore/qobject.html#eventFilter)。以下是代码应如何显示的示例:

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

编辑:根据我的理解,您只需要在QLineEdit中显示一个描述其角色的默认文本。这是使用placeholderText的好机会。以下是修改后使用它的代码(不再需要eventFilter方法):

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()