PyQt5 QSpinBox – 当对象名称改变时添加动作
在这篇文章中,我们将看到当旋转盒子的对象名称改变时,我们如何做一些事情,对象名称基本上是给旋转盒子的对象的名称,当我们在PyQt5应用程序中借助对象名称在findChild方法的帮助下找到该对象。对象名称可以在setObjectName方法的帮助下设置给旋转盒。
实施步骤 —
1.创建一个旋转盒
2.设置其对象名称
3.在标签的帮助下显示对象名称
4.当对象名称改变时,在旋转盒上添加动作,使旋转盒的后缀改变
5.创建一个按钮
6.在按钮上添加动作,改变旋钮的对象名称。
为了在对象名称改变时添加动作,我们使用 objectNameChanged.connect 方法。
语法:spin_box.objectNameChanged.connect(方法名)
参数:它接受方法名称作为参数
执行的动作:它将调用通过的方法
以下是实现方法
# 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 suffix to spin
self.spin.setSuffix(" Spin Box")
# name
name = "Geeky"
# setting up object name
self.spin.setObjectName(name)
# adding action when the spin box object name is changed
self.spin.objectNameChanged.connect(self.spin_method)
# creating label
self.label = QLabel(self)
# setting geometry
self.label.setGeometry(100, 200, 300, 40)
# getting object name
get_name = self.spin.objectName()
# setting text to the label
self.label.setText("Object Name : " + get_name)
# creating a push button
push = QPushButton("Press", self)
# adding action to the push button
push.pressed.connect(self.push_method)
# method called when object name is changed
def spin_method(self):
# setting suffix
self.spin.setSuffix(" Name changed")
# method called by push button
def push_method(self):
# setting object name of spin box
self.spin.setObjectName("New")
# getting object name
get_name = self.spin.objectName()
# showing this new name to label
self.label.setText("Object Name : " + get_name)
# create pyqt5 app
App = QApplication(sys.argv)
# create the instance of our Window
window = Window()
# start the app
sys.exit(App.exec())