我有一个QLabel,我使用QPixmap设置QImage。我的图片尺寸为512x512,我希望它保持这个尺寸而不是拉伸/收缩。
创建我的QLabel后,它的大小显示为512,512,但我可以看到它已拉伸。也许有办法防止像素图的拉伸/尺寸变化?我在这里做错了什么?
class ImageLabel(QtWidgets.QLabel):
def __init__(self, image):
QtWidgets.QLabel.__init__(self)
self._zoom = 1.0
self.setContentsMargins(0, 0, 0, 0)
self.setAlignment(QtCore.Qt.AlignCenter)
self.setGeometry(0, 0, 512, 512)
self.resize(512, 512)
# set image
img = qimage2ndarray.array2qimage(image)
qimg = QtGui.QPixmap.fromImage(img)
self._displayed_pixmap = QtGui.QPixmap(qimg)
# scale image to fit label
w, h = self.width(), self.height()
self._displayed_pixmap.scaled(w, h, QtCore.Qt.KeepAspectRatio)
self.setAlignment(QtCore.Qt.AlignCenter)
self.setScaledContents(True)
self.setMinimumSize(512, 512)
self.show()
def paintEvent(self, paint_event):
painter = QtGui.QPainter(self)
painter.drawPixmap(self.rect(), self._displayed_pixmap)
def sizeHint(self):
return QtCore.QSize(512, 512)
class MyWindow(QtWidgets.QWidget):
def __init__(self, image):
QtWidgets.QWidget.__init__(self)
main_layout = QtWidgets.QVBoxLayout()
main_layout.setContentsMargins(0,0,0,0)
self._image_label = ImageLabel(image)
main_layout.addStretch()
main_layout.addWidget(self._image_label)
main_layout.addStretch()
print(self._image_label.size()) # PyQt5.QtCore.QSize(512, 512)
self.setLayout(main_layout)
正如您所看到的,我尝试了调整大小的所有变化。 显示时,标签实际上是〜(1180,512)
的大小