PyQt5 QSpinBox – 将两个旋转框相互连接
在本文中,我们将看到如何将两个旋转框相互连接,这样一个旋转框中的每次值变化都应该反映在另一个旋转框中,例如当我们固定图像的宽高比并允许用户使用旋转框设置宽度和高度,因为比例是固定的,因此任何维度的变化也应该反映在另一个维度上。
例子 :
两个相互连接的旋转框,因此对于任何旋转框中发生的每次值变化,值都应保持相等。
Steps for implementation :
1. Create two spin box
2. Add geometry to both the spin box
3. Add action to each spin box using valueChanged signal
4. Inside the first spin box action get the current value of spin box and set this value to the second spin box
5. Inside the second spin box action get the current value of spin box and set that value to the first spin box
下面是实现
# 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())
输出 :