PyQt5 – 如何清除标签的内容|清除和设置文本方法
在这篇文章中,我们将看到如何轻松地清除/删除PyQt5应用程序中标签的内容。这可以通过两种方式实现
- 使用clear()方法,这将清除标签的内容。
- 使用setText()方法,并传递一个空白字符串,这将用空白字符串更新内容。
使用clear()方法 –
语法: label.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())
输出 :
使用setText()方法-
语法: label.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())
输出 :