PyQt5的QSpinBox – 根据用户指令删除它
在这篇文章中,我们将看到如何在用户命令时删除旋转盒,而在设计一个应用程序时,如果在关闭小部件时不注意,它有可能会消耗大量的空间/内存。基于QObject的类被设计成(可选择地)在一个层次结构中链接在一起。当一个顶层对象被删除时,Qt将自动删除其所有子对象。为了明确地删除旋转盒的引用,我们使用deleteLater方法。
语法: spin_box.deleteLater()
参数: 它不需要参数
执行的动作: 它从内存中删除/移除自旋盒的引用。
实施步骤:
- 创建一个自旋盒
-
创建一个标签来显示旋转盒的状态
-
创建按钮
-
为按钮添加动作
-
在动作中删除旋转盒的引用,并更新标签的文本
以下是实施步骤
# 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")
# creating label
self.label = QLabel(self)
# setting geometry
self.label.setGeometry(100, 200, 300, 40)
# setting text to the label
self.label.setText("Spin box will delete when button get pressed")
# creating a push button
push = QPushButton("Press", self)
# adding action to the push button
push.pressed.connect(self.push_method)
# method called by push button
def push_method(self):
# deleting the spin box
self.spin.deleteLater()
# showing this new name to label
self.label.setText("Spin box is deleted")
# create pyqt5 app
App = QApplication(sys.argv)
# create the instance of our Window
window = Window()
# start the app
sys.exit(App.exec())