思路:每次输入框内容改变,都重置 QTimer 倒计时为 3 秒;当持续 3 秒无输入后,QTimer 超时,获取当前输入框内容。
UI 代码(untitled.py):
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(400, 300)
self.horizontalLayout = QtWidgets.QHBoxLayout(Form)
self.horizontalLayout.setObjectName("horizontalLayout")
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.plain_text_edit = QtWidgets.QPlainTextEdit(Form)
self.plain_text_edit.setObjectName("plainTextEdit")
self.verticalLayout.addWidget(self.plain_text_edit)
self.label = QtWidgets.QLabel(Form)
self.label.setText("")
self.label.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.label.setObjectName("label")
self.verticalLayout.addWidget(self.label)
self.verticalLayout.setStretch(0, 1)
self.verticalLayout.setStretch(1, 1)
self.horizontalLayout.addLayout(self.verticalLayout)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
逻辑代码:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from untitled import Ui_Form # UI 代码:untitled.py
class MyWindow(QWidget, Ui_Form):
def __init__(self):
super(MyWindow, self).__init__()
self.setupUi(self)
self.plain_text_edit.textChanged.connect(self.reset_timer) # 检测输入框文本改变
self.timer = QTimer()
self.timer.setSingleShot(True) # 设置为单次触发,即定时器超时后只触发一次,避免多余触发
self.timer.timeout.connect(self.get_text) # 超时(3000ms)后获取当前输入框内容
def reset_timer(self):
print("重置 timer 倒计时为 3000ms")
self.timer.start(3000)
def get_text(self):
print("读取 plain_text_edit 文本,并设置到 label 中")
self.label.setText(self.plain_text_edit.toPlainText())
app = QApplication(sys.argv)
mw = MyWindow()
mw.show()
sys.exit(app.exec_())