PyQt5 QSpinBox – 添加循环
在本文中,我们将看到如何向旋转框添加循环,当我们默认创建旋转框时,当它达到最大值时,它不能再增加,类似地,当它达到最小值时,它不能减少不再。通过向微调框添加循环,值会在达到最大值或最小值后自行重复。
Implementation steps :
1. Create a window
2. Create a spin box
3. Set range of the spin box such that it has one extra value for minimum and maximum value for example if we want values from 0 to 100 set range to -1 to 101
4. Add action to the spin box such that every time its value changes action should get called
5. Inside the action get the current value of the spin box.
6. Check if current value is equal to the minimum value then set current value of spin box to maximum value – 1
7. Else check if current value is equal to maximum value then make current value of spin box to minimum + 1
下面是实现
# importing libraries
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
# setting title
self.setWindowTitle("Python ")
# setting geometry
self.setGeometry(100, 100, 600, 400)
# calling method
self.UiComponents()
# showing all the widgets
self.show()
# method for widgets
def UiComponents(self):
# creating spin box
self.spin = QSpinBox(self)
# setting geometry to spin box
self.spin.setGeometry(100, 100, 150, 40)
# setting range to the spin box
self.spin.setRange(-1, 11)
# setting prefix to spin
self.spin.setPrefix("Value : ")
# add action to this spin box
self.spin.valueChanged.connect(self.action_spin)
# method called after editing finished
def action_spin(self):
# getting current value of spin box
current = self.spin.value()
# checking if current value is minimum
if current == -1:
# setting spin box value to maximum - 1
self.spin.setValue(10)
# checking if current value is maximum
elif current == 11:
# setting spin box value to minimum + 1
self.spin.setValue(0)
# create pyqt5 app
App = QApplication(sys.argv)
# create the instance of our Window
window = Window()
# start the app
sys.exit(App.exec())
输出 :