写一段QlineEdit文本框中预设内容的代码,其中预设内容设置为点击QlineEdit 文本框就消失
时间: 2023-05-14 20:06:09 浏览: 112
下面是一段可以实现预设内容的 QlineEdit 文本框的代码:
```python
from PyQt5.QtWidgets import QApplication, QLineEdit, QWidget, QVBoxLayout
from PyQt5.QtCore import Qt
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
vbox = QVBoxLayout()
self.lineedit = QLineEdit()
self.lineedit.setPlaceholderText("请输入内容")
self.lineedit.installEventFilter(self)
vbox.addWidget(self.lineedit)
self.setLayout(vbox)
def eventFilter(self, obj, event):
if obj == self.lineedit and event.type() == Qt.FocusInEvent:
self.lineedit.clear()
return super().eventFilter(obj, event)
if __name__ == '__main__':
app = QApplication([])
w = MyWidget()
w.show()
app.exec_()
```
这段代码中,我们创建了一个 MyWidget 类,继承自 QWidget 类。在 MyWidget 类的 initUI 方法中,我们创建了一个 QVBoxLayout 布局,并在其中添加了一个 QLineEdit 文本框。我们通过调用 setPlaceholderText 方法设置了预设内容为 "请输入内容"。我们还通过调用 installEventFilter 方法,将自定义的 eventFilter 方法安装到 QLineEdit 上,以便在用户点击文本框时清空预设内容。在 eventFilter 方法中,我们判断如果当前对象是 QLineEdit,并且事件类型是 FocusInEvent,就清空文本框内容。最后,我们创建了一个 QApplication 实例,并将 MyWidget 实例显示出来。