To add borders to a QLabel in PyQt5, you have two main methods:
### Method 1: Using QFrame to Create Borders
1. **Import Libraries:**
```python
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QFrame
import sys
```
2. **Create a Custom Class Inheriting from QWidget:**
```python
class MainWindow(QWidget):
def __init__(self):
super().__init__()
# Set window title and size
self.setWindowTitle('PyQt5 QLabel with Border')
self.resize(300, 200)
# Create a vertical layout
layout = QVBoxLayout()
# Create QLabel and set text
label = QLabel('Hello, PyQt5!')
# Create QFrame as border
frame = QFrame()
frame.setFrameShape(QFrame.Box) # Set border shape
frame.setFrameShadow(QFrame.Sunken) # Set border shadow
# Add QLabel to QFrame
frame.setLayout(layout)
frame.addWidget(label)
# Add QFrame to layout
layout.addWidget(frame)
# Set window layout
self.setLayout(layout)
```
3. **Create Application Instance and Run:**
```python
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
### Method 2: Using QLabel's Stylesheet (QSS) to Add Borders
1. **Import Libraries:**
```python
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel
from PyQt5.QtCore import Qt
import sys
```
2. **Create a Custom Class Inheriting from QWidget:**
```python
class MainWindow(QWidget):
def __init__(self):
super().__init__()
# Set window title and size
self.setWindowTitle('PyQt5 QLabel with Border')
self.resize(300, 200)
# Create a vertical layout
layout = QVBoxLayout()
# Create QLabel and set text
label = QLabel('Hello, PyQt5!')
# Set QLabel's stylesheet to add border
label.setStyleSheet("border: 2px solid red;")
# Add QLabel to layout
layout.addWidget(label)
# Set window layout
self.setLayout(layout)
```
3. **Create Application Instance and Run:**
```python
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
Both methods achieve the effect of adding borders to a QLabel in PyQt5.
If you have any further questions, feel free to ask!
本文链接:https://www.24zzc.com/news/171324109968158.html