PyQt5 – 设置和访问一个标签的名称
在设计一个Gui(图形用户界面)应用程序时,我们通常会制作很多标签。对于后端代码员来说,要区分这些标签是很困难的。为了克服这种情况,需要设置标签名称,例如,在数百个标签中,我们可以通过设置它们的名称来区分它们,如一些是 “信息 “标签,一些是 “警告 “标签,就像这样。标签通常是一个图形控制元素,在表单中显示文本。它通常是一个静态控件;没有互动性。标签一般用于识别附近的文本框或其他小部件。
要设置名称——“标签”,需要在 “标签 “中设置 “名称”。
语法: label.setAccessibleName(name)
参数: 它以字符串为参数。
返回: 没有返回值。
要访问名称 –
语法: label.setaccessibleName()
参数: 它不需要参数。
返回: 它返回字符串。
代码。
# importing the required libraries
from PyQt5.QtWidgets import *
from PyQt5 import QtCore
from PyQt5 import QtGui
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
# set the title
self.setWindowTitle("Name")
# 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;")
# setting up the name of label_1
self.label_1.setAccessibleName("Info")
# getting name of label_1
name = self.label_1.setaccessibleName()
# new label to display name
self.label_2 = QLabel(name, self)
self.label_2.move(100, 130)
self.label_2.adjustSize()
# 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())
输出 :