QLabel显示图片契合背景
时间: 2024-01-11 22:05:38 浏览: 99
要使QLabel显示的图片与背景契合,可以使用以下方法:
1. 在创建QLabel时,将其背景设置为透明:
```python
label.setStyleSheet("background-color: transparent;")
```
2. 将QLabel的大小设置为图片的大小:
```python
label.setFixedSize(image.width(), image.height())
```
3. 将QLabel的对齐方式设置为居中:
```python
label.setAlignment(Qt.AlignCenter)
```
完整示例代码:
```python
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# 加载图片
image = QPixmap('image.png')
# 创建QLabel并设置背景为透明
label = QLabel(self)
label.setStyleSheet("background-color: transparent;")
# 设置QLabel大小为图片大小
label.setFixedSize(image.width(), image.height())
# 将图片设置为QLabel的内容
label.setPixmap(image)
# 将QLabel对齐方式设置为居中
label.setAlignment(Qt.AlignCenter)
self.setGeometry(300, 300, image.width(), image.height())
self.setWindowTitle('Example')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
```
阅读全文
相关推荐


















