问题
Let's say we have a QLabel with QPixmap
label = QLabel
Pixmap = QPixmap('filepath')
label.setPixmap(Pixmap)
I already mentioned that by using
label.setScaledContents(True)
We can force image to be autoscaled to label size (And widget's one if label autoscaled to it) Without using it, image gona be displayed in it's full size, not depending on window or label's one. Now i want it to be autoscaled to label's size, but keeping it's aspect ratio.
回答1:
Try it:
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_())
来源:https://stackoverflow.com/questions/53560035/pyqt-different-image-autoscaling-modes