假设我们有一个带有QPixmap的QLabel
label = QLabel
Pixmap = QPixmap('filepath')
label.setPixmap(Pixmap)
我已经提到使用
label.setScaledContents(True)
我们可以强制将图像自动缩放到标签大小(如果标签自动缩放到标签大小,则为小部件的) 如果不使用它,图像将以原尺寸显示,而不取决于窗口或标签的尺寸。现在,我希望将其自动缩放为标签的大小,但要保持其长宽比。
答案 0 :(得分:0)
尝试一下:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
centralWidget = QWidget()
self.setCentralWidget(centralWidget)
self.label = QLabel()
self.pixmap = QPixmap("head.jpg")
self.label.setPixmap(self.pixmap.scaled(self.label.size(),
Qt.KeepAspectRatio, Qt.SmoothTransformation))
self.label.setSizePolicy(QSizePolicy.Expanding,
QSizePolicy.Expanding)
self.label.setAlignment(Qt.AlignCenter)
self.label.setMinimumSize(100, 100)
layout = QGridLayout(centralWidget)
layout.addWidget(self.label)
def resizeEvent(self, event):
scaledSize = self.label.size()
scaledSize.scale(self.label.size(), Qt.KeepAspectRatio)
if not self.label.pixmap() or scaledSize != self.label.pixmap().size():
self.updateLabel()
def updateLabel(self):
self.label.setPixmap(self.pixmap.scaled(
self.label.size(), Qt.KeepAspectRatio,
Qt.SmoothTransformation))
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())