📜  PyQt5 - 如何清除标签的内容 | clear 和 setText 方法

📅  最后修改于: 2022-05-13 01:54:53.175000             🧑  作者: Mango

PyQt5 - 如何清除标签的内容 | clear 和 setText 方法

在本文中,我们将了解如何轻松清除/擦除 PyQt5 应用程序标签的内容。这可以通过两种方式完成——

  1. 使用clear()方法,这将清除标签的内容。
  2. 使用setText()方法并传递一个空白字符串,这将使用空白字符串更新内容。

使用clear()方法 –

代码 :

# importing the required libraries
  
from PyQt5.QtWidgets import * 
from PyQt5 import QtCore
from PyQt5.QtGui import * 
import sys
  
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
          
        # set the title
        self.setWindowTitle("Label")
  
        # setting  the geometry of window
        self.setGeometry(0, 0, 400, 300)
  
        # creating a label widget
        self.label_1 = QLabel("Label", self)
  
        # moving position
        self.label_1.move(100, 100)
  
        # setting up border
        self.label_1.setStyleSheet("border: 1px solid black;")
  
        # creating a label widget
        self.label_2 = QLabel("Hidden Label", self)
  
        # moving position
        self.label_2.move(100, 150)
  
        # setting up border
        self.label_2.setStyleSheet("border: 1px solid black;")
  
        # clearing the data
        self.label_2.clear()
  
  
        # show all the widgets
        self.show()
  
# create pyqt5 app
App = QApplication(sys.argv)
  
# create the instance of our Window
window = Window()
  
# start the app
sys.exit(App.exec())

输出 :
pyqt-清除标签

使用setText()方法 –

代码 :

# importing the required libraries
  
from PyQt5.QtWidgets import * 
from PyQt5 import QtCore
from PyQt5.QtGui import * 
import sys
  
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
  
        # set the title
        self.setWindowTitle("Label")
  
        # setting  the geometry of window
        self.setGeometry(0, 0, 400, 300)
  
        # creating a label widget
        self.label_1 = QLabel("Label", self)
  
        # moving position
        self.label_1.move(100, 100)
  
        # setting up border
        self.label_1.setStyleSheet("border: 1px solid black;")
  
        # creating a label widget
        self.label_2 = QLabel("Hidden Label", self)
  
        # moving position
        self.label_2.move(100, 150)
  
        # setting up border
        self.label_2.setStyleSheet("border: 1px solid black;")
  
        # replacing content with blank
        self.label_2.setText("")
  
  
        # show all the widgets
        self.show()
  
  
# create pyqt5 app
App = QApplication(sys.argv)
  
# create the instance of our Window
window = Window()
  
# start the app
sys.exit(App.exec())

输出 :
pyqt-label-setText