PyQt5 – 如何在 QLabel 上添加边框?
当我们在 PyQt5 中创建 Label 时,我们可以看到没有像 Push Buttons 中那样的边框,在本文中我们将看到如何为 Label 添加边框。
为了给标签添加边框,我们将使用label.setStyleSheet()
方法,这将给标签添加边框,我们也可以设置边框的粗细和颜色。
Syntax : label.setStyleSheet(“border: 1px solid black;”)
Argument : It takes string as a argument.
Action performed : This will create a border on label with thickness of 1px and color will be black.
下面是Python的实现——
# importing the required libraries
from PyQt5.QtWidgets import *
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
# by default label will display at top left corner
self.label_1 = QLabel('It is Label 1', self)
# moving position
self.label_1.move(100, 100)
# setting up border
self.label_1.setStyleSheet("border: 1px solid black;")
# creating a label widget
# by default label will display at top left corner
self.label_2 = QLabel('It is Label 2', self)
# moving position
self.label_2.move(100, 200)
# setting up border
self.label_2.setStyleSheet("border: 3px solid blue;")
# 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())
输出 :