PyQt5 – Creating String Spin Box
In this article we will see how we can create a spin box which have string values, by default the spin box contains only integer values. String Spin box is a spin box which have string values to select from the given string values.
In order to create a String Spin Box we have create a custom class which inherits the QSpinBox class, below is the String Spin Box class syntax
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
# custom class for String Spin Box class StringBox(QSpinBox): # constructor def __init__(self, parent=None): super(StringBox, self).__init__(parent) # string values strings = ["a", "b", "c", "d", "e", "f", "g"] # calling setStrings method self.setStrings(strings) # 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]
Explanation : The basic idea of this class is that we create a custom class which inherits the spin box class that’s why it has all the abilities of normal spin box but instead of displaying integer it display the string value. We have created dictionary such that for each string it has a integer key and the range of spin box is the number of string values and with the help of overwriting the textFromValue method it shows string instead of the integer.
Below is the implementation