PyQt5 StringSpinBox – Looping the strings
In this article we will see how we can make the string values repeat themselves when the last value reaches it should go back to the first value similarly when value is decremented after first value it should go back to the last value. In order to do this we have to change the custom class code of the StringSpinBox.
Below is the code for the custom StringSpinBox class
# custom class for String Spin Box class StringBox(QSpinBox): # constructor def __init__(self, parent=None): super(StringBox, self).__init__(parent) # list of strings strings = ["a", "b", "c", "d", "e", "f", "g"] # calling set Strings method with # adding blank value in front and in end self.setStrings(["BLANK"] + strings + ["BLANK"]) # show first value from index 1 self.setValue(1) def reset_spin(self): if self.value() == len(self.strings()) - 1: self.setValue(0) # method setString # similar to set value method def setStrings(self, strings): # making strings list strings = list(strings) # making tuple from the string list self._strings = tuple(strings) # creating a dictionary self._values = dict(zip(strings, range(len(strings)))) # setting range to it the spin box self.setRange(0, len(strings)-1) # overwriting the textFromValue method def textFromValue(self, value): # returning string from index # _string = tuple return self._strings[value] # overwriting the stepBy method # method that get called when values get incremented or decremented def stepBy(self, step): # checking if current value is 1 and step is -1 # step = -1 means decrement if self.value() == 1 and step == -1: # set current value to maximum self.setValue(self.maximum()) # checking if current value is maximum -1 and step is 1 # step = 1 means Increment elif self.value() == self.maximum() - 1 and step == 1: # setting current value to 0 self.setValue(0) # calling stepBy method of QSpinBox QSpinBox.stepBy(self, step)
Explanation : Inside the String spin box custom class overwrite the stepBy method which get called when increment or decrement takes place there check the that if there is decrement and current value is minimum then change its value to maximum similarly if there is increment and it is currently at maximum value then change its value to minimum -1 value.
Below is the implementation
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course