我正在使用 USB 条形码扫描仪设置 Qt lineEdit 字段的文本,然后将其文本用于 GUI 的其他功能(具体来说,文本是名称用户当前正在测量的 sample 的名称,稍后将保存为文件名)。
我的问题是我想用下一个扫描的 barcode 动态覆盖 lineEdit 字段中的当前文本,没有用户在扫描前手动删除当前文本。因为我只是将扫描仪用作键盘仿真器,而不是从中正确读取串行信息,所以用户必须在扫描前单击文本字段。
我不知道哪个 lineEdit 连接操作会允许以下操作:
from PyQt4 import QtGui
# add widgets etc
# ...........
# lineEdit part
self.mylineEdit = QtGui.QLineEdit()
#initialise to empty string on start up
self.mylineEdit.setText(' ')
#barcode scans here and then a returnPressed is registered
#connect to a function
self.mylineEdit.returnPressed.connect(self.set_sample_name) #here is where I want to delete the previous entry without backspacing by hand
#set the sample name variable
def set_sample_name(self):
self.sample_name = self.mylindEdit.text()
我想知道有没有办法在扫描下一个条形码之前删除文本框中的前一个字符串? (没有文本字段暂时为空)..
谢谢。
PS - 在 Ubuntu 16.04 上使用 python3.5.2 和 pyQT4
请您参考如下方法:
from PyQt5 import QtWidgets,QtCore
import sys
import os
class window(QtWidgets.QMainWindow):
def __init__(self):
super(window,self).__init__()
self.mylineEdit = QtWidgets.QLineEdit()
self.mylineEdit2 = QtWidgets.QLineEdit()
self.startNew=1
#initialise to empty string on start up
self.mylineEdit.setText(' ')
#barcode scans here and then a returnPressed is registered
#connect to a function
self.mylineEdit.returnPressed.connect(self.set_sample_name) #here is where I want to delete the previous entry without backspacing by hand
self.mylineEdit.textChanged.connect(self.delete_previous)
centwid=QtWidgets.QWidget()
lay=QtWidgets.QVBoxLayout()
lay.addWidget(self.mylineEdit)
lay.addWidget(self.mylineEdit2)
centwid.setLayout(lay)
self.setCentralWidget(centwid)
self.show()
#set the sample name variable
def set_sample_name(self):
self.sample_name = self.mylineEdit.text()
print(self.sample_name)
self.startNew=1
def delete_previous(self,text):
if self.startNew:
self.mylineEdit.setText(text[-1])
self.startNew=0
app=QtWidgets.QApplication(sys.argv)
ex=window()
sys.exit(app.exec_())
一旦返回按下信号被执行,你就可以改变标志 self.startNew=1 这将确保每当文本发生变化时它都会检查标志并在新的时候删除完整的字符串输入条形码。我已经在 PyQt5 中完成了,但概念将保持不变。 该功能在 self.myLineEdit 中实现。
