pyqt5 判断lineedit内容长度
时间: 2023-12-22 21:05:37 浏览: 27
你可以通过 `QLineEdit` 类的 `text()` 方法获取当前文本框中的文本,然后使用 `len()` 函数计算文本的长度。下面是一个简单的例子:
```python
from PyQt5.QtWidgets import QApplication, QLineEdit, QWidget, QVBoxLayout
import sys
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.lineedit = QLineEdit(self)
self.lineedit.textChanged.connect(self.check_length)
layout = QVBoxLayout(self)
layout.addWidget(self.lineedit)
self.setLayout(layout)
def check_length(self):
text = self.lineedit.text()
if len(text) > 10:
print("Text is too long!")
if __name__ == '__main__':
app = QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())
```
在上面的例子中,我们创建了一个 `QLineEdit` 对象,并将其添加到一个 `QVBoxLayout` 布局中。然后,我们连接了 `textChanged` 信号到 `check_length()` 槽函数。当用户在文本框中输入文本时,`check_length()` 函数会被调用,并使用 `len()` 函数计算文本的长度。如果文本的长度超过了 10 个字符,函数会输出一条消息。