PyQt5 QSpinBox – 互相连接两个自旋盒
在这篇文章中,我们将看到如何将两个自旋盒相互连接,使一个自旋盒中的每一个值的变化也反映在另一个自旋盒中,例如,当我们固定了图片的宽高比例,并允许用户使用自旋盒来设置宽度和高度,由于比例是固定的,因此任何尺寸的变化也应该反映在另一个尺寸中。
例子:
两个相互连接的旋钮箱,当任何一个旋钮箱的值发生变化时,其值应保持相等。
实施步骤。
1.创建两个自旋盒
2.2. 为两个自旋盒添加几何图形
3.使用valueChanged信号为每个自旋盒添加动作
4.在第一个自旋盒的动作中获得自旋盒的当前值,并将此值设置到第二个自旋盒中
5.在第二个旋转盒的动作中,获得旋转盒的当前值,并将该值设置到第一个旋转盒中。
以下是执行情况
# 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.spin1 = QSpinBox(self)
# setting geometry to spin box
self.spin1.setGeometry(100, 100, 150, 40)
# setting prefix to spin
self.spin1.setPrefix("Width : ")
# add action to this spin box
self.spin1.valueChanged.connect(self.action_spin1)
# creating another spin box
self.spin2 = QSpinBox(self)
# setting geometry to spin box
self.spin2.setGeometry(300, 100, 150, 40)
# setting prefix to spin box
self.spin2.setPrefix("Height : ")
# add action to this spin box
self.spin2.valueChanged.connect(self.action_spin2)
# method called after editing finished
def action_spin1(self):
# getting current value of spin box
current = self.spin1.value()
# setting this value to second spin box
self.spin2.setValue(current)
# method called after editing finished
def action_spin2(self):
# getting current value of spin box
current = self.spin2.value()
# setting this value to the first spin box
self.spin1.setValue(current)
# create pyqt5 app
App = QApplication(sys.argv)
# create the instance of our Window
window = Window()
# start the app
sys.exit(App.exec())