我正在使用 PYQT5 创建一个 GUI 来显示滑块,并且我想要一种有效的方法来创建许多相同类型但名称不同的滑块。目前,我必须复制粘贴相同的代码来制作每个单独的滑块,因此我的代码过长。
这是 3 个滑块当前的样子:
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
self.width = 1120
self.height = 527
MainWindow.resize(self.width, self.height)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
self.horizontalLayout.setObjectName("horizontalLayout")
self.label = QtWidgets.QLabel(self.centralwidget)
self.verticalSlider1 = QtWidgets.QSlider(self.shape_tab)
self.shape_minimum = 1
self.shape_maximum = 2000000
self.verticalSlider1.setRange(self.shape_minimum, self.shape_maximum)
self.verticalSlider1.setGeometry(QtCore.QRect(40, 40, 31, 251))
self.verticalSlider1.setOrientation(QtCore.Qt.Vertical)
self.verticalSlider1.setMaximum(self.shape_maximum)
self.verticalSlider1.setObjectName("verticalSlider1")
self.verticalSlider2 = QtWidgets.QSlider(self.shape_tab)
self.shape_minimum = 1
self.shape_maximum = 2000000
self.verticalSlider2.setRange(self.shape_minimum, self.shape_maximum)
self.verticalSlider2.setGeometry(QtCore.QRect(80, 40, 31, 251))
self.verticalSlider2.setOrientation(QtCore.Qt.Vertical)
self.verticalSlider2.setMaximum(self.shape_maximum)
self.verticalSlider2.setObjectName("verticalSlider2")
self.verticalSlider3 = QtWidgets.QSlider(self.shape_tab)
self.shape_minimum = 1
self.shape_maximum = 2000000
self.verticalSlider3.setRange(self.shape_minimum, self.shape_maximum)
self.verticalSlider3.setGeometry(QtCore.QRect(120, 40, 31, 251))
self.verticalSlider3.setOrientation(QtCore.Qt.Vertical)
self.verticalSlider3.setMaximum(self.shape_maximum)
self.verticalSlider3.setObjectName("verticalSlider3")
我必须总共创建 199 个滑块,它们具有相同的属性。它们仅在名称和 UI 中的位置不同(setGeometry(QtCore.QRect()))。创建这么多滑块的最佳方法是什么,而无需复制和粘贴相同的代码 199 次并更改名称。
我想创建一个 Slider 作为类对象,但我认为它不适用于 UI_MainWindow 类。我也不确定 for 循环如何工作。任何想法或意见将不胜感激!