import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
def pressenter():
print ("Enter pressed")
def window():
app = QApplication(sys.argv)
win = QWidget()
editbox = QLineEdit()
editbox.setValidator(QDoubleValidator(0.99,99.99,2))
eform = QFormLayout()
eform.addRow("Enter text: ",editbox)
editbox.editingFinished.connect(pressenter)
win.setLayout(eform)
win.setWindowTitle("My Test Window")
win.show()
sys.exit(app.exec_())
if __name__ == '__main__':
window()
我有一个简单的编辑框,当我按Enter键时我希望光标退出编辑框,这样我就知道我的输入被接受了。这意味着当我想再次编辑时,我特别需要再次选择编辑框。我尝试搜索这个问题,但是我不是英语天生的人,也许这是我的问题,但是我找不到很好的答案。
我目前注意到两个问题:我需要验证器来防止按回车键,另一个问题是pressenter()函数可能应该执行某些操作,但是我不知道焦点方法会做什么。
答案 0 :(得分:0)
您可以将焦点设置到主窗口: (仅当输入有效时,焦点才会切换,这是您想要的行为吗?)
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
def pressenter(win):
win.setFocus()
def window():
app = QApplication(sys.argv)
win = QWidget()
editbox = QLineEdit()
editbox.setValidator(QDoubleValidator(0.99,99.99,2))
eform = QFormLayout()
eform.addRow("Enter text: ",editbox)
editbox.editingFinished.connect(lambda: pressenter(win))
win.setLayout(eform)
win.setWindowTitle("My Test Window")
win.show()
sys.exit(app.exec_())
if __name__ == '__main__':
window()
如果不接受输入,您还可以在pressenter
函数中进行验证并重置编辑框:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
def pressenter(win, editbox):
val = QDoubleValidator(0.99,99.99,2)
if val.validate(editbox.text(),0)[0] == QValidator.Acceptable:
win.setFocus()
else:
editbox.setText('')
def window():
app = QApplication(sys.argv)
win = QWidget()
editbox = QLineEdit()
eform = QFormLayout()
eform.addRow("Enter text: ", editbox)
editbox.editingFinished.connect(lambda: pressenter(win, editbox))
win.setLayout(eform)
win.setWindowTitle("My Test Window")
win.show()
sys.exit(app.exec_())
if __name__ == '__main__':
window()