Since the keys can use more than one character, a possible solution is to use the textChanged(text)
signal and call the function to compute the shifts afterwards.
The fact, though, is that the two existing functions are actually flawed: they almost do the same thing, but don't consider the two fields as they should.
I suggest you to merge those functions and use the textChanged
to "reset" the value only when a valid key is entered. Note that this implies a logic that is not immediate to understand (even for the user) and might also cause some confusion
class OrOh(QWidget, oroh):
def __init__(self):
QWidget.__init__(self)
self.setupUi(self)
self.shifts = {"m":7, "s":7, "v":7, "t":7, "e":3, "le":5, "ld":12,
"n":12, "ln":14, "mn":19, "en":17, "me":10, "f":24}
self.lin_sh1.returnPressed.connect(self.computeShift)
self.lin_sh2.returnPressed.connect(self.computeShift)
self.lin_sh1.textChanged.connect(self.checkText)
self.lin_sh2.textChanged.connect(self.checkText)
def checkText(self):
lin1 = self.lin_sh1.text()
lin2 = self.lin_sh2.text()
if self.lbl_shifts.text() and (not lin1 or not lin2):
self.computeShift()
def computeShift(self):
lin1 = self.lin_sh1.text()
lin2 = self.lin_sh2.text()
if ((lin1 in self.shifts and not lin2) or
(lin2 in self.shifts and not lin1) or
(lin1 in self.shifts and lin2 in self.shifts)):
shift = self.shifts.get(lin1, 0) + self.shifts.get(lin2, 0)
self.lbl_shifts.setText(str(shift))
I would suggest you to add some validation logic instead, or at least always use the textChanged
signal. A simple solution would be to change the text color whenever the text entered is not in the dictionary, and eventually clear it when the focus changes:
class OrOh(QWidget, oroh):
def __init__(self):
QWidget.__init__(self)
self.setupUi(self)
self.shifts = {"m":7, "s":7, "v":7, "t":7, "e":3, "le":5, "ld":12,
"n":12, "ln":14, "mn":19, "en":17, "me":10, "f":24}
self.lin_sh1.textChanged.connect(self.computeShift)
self.lin_sh2.textChanged.connect(self.computeShift)
self.lin_sh1.editingFinished.connect(lambda: self.checkField(self.lin_sh1))
self.lin_sh2.editingFinished.connect(lambda: self.checkField(self.lin_sh2))
def checkField(self, field):
if not field.text() in self.shifts:
field.setText('')
def computeShift(self):
shift = 0
for field in (self.lin_sh1, self.lin_sh2):
value = self.shifts.get(field.text(), 0)
if field.text() and not value:
field.setStyleSheet('color: red;')
else:
field.setStyleSheet('')
shift += self.shifts.get(field.text(), 0)
self.lbl_shifts.setText(str(shift))
Another possibility would be to use an editable QComboBox (with the insert policy set to NoInsert
) and check the shift only when the inserted text is in the list.