如何缩放QPixmap以保留纵横比并将图像居中



我想在QMdiArea中使用图像(svg文件(作为背景。我将图像加载为QPixmap,并使用在resizeEvent方法中将其缩放为QMdiArea的大小

self._background_scaled = self._background.scaled(self.size(), QtCore.Qt.KeepAspectRatio)
self.setBackground(self._background_scaled)

但这会将图像放在左上角,并在X或Y方向重复。我希望图像居中。

如何缩放QPixmap,使其保持纵横比并调整大小,然后添加边框以获得确切的大小?

setBackground((方法接受基于您传递给它的QPixmap构建的QBrush,但如果QBrush是基于QPixmap创建的,它将创建纹理(重复元素(,并且无法更改该行为。因此,解决方案是覆盖paintEvent方法并直接绘制QPixmap:

import sys
from PySide2 import QtCore, QtGui, QtWidgets

def create_pixmap(size):
pixmap = QtGui.QPixmap(size)
pixmap.fill(QtCore.Qt.red)
painter = QtGui.QPainter(pixmap)
painter.setBrush(QtCore.Qt.blue)
painter.drawEllipse(pixmap.rect())
return pixmap

class MdiArea(QtWidgets.QMdiArea):
def __init__(self, parent=None):
super().__init__(parent)
pixmap = QtGui.QPixmap(100, 100)
pixmap.fill(QtGui.QColor("transparent"))
self._background = pixmap
@property
def background(self):
return self._background
@background.setter
def background(self, background):
self._background = background
self.update()
def paintEvent(self, event):
super().paintEvent(event)
painter = QtGui.QPainter(self.viewport())
background_scaled = self.background.scaled(
self.size(), QtCore.Qt.KeepAspectRatio
)
background_scaled_rect = background_scaled.rect()
background_scaled_rect.moveCenter(self.rect().center())
painter.drawPixmap(background_scaled_rect.topLeft(), background_scaled)

if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mdiarea = MdiArea()
mdiarea.show()
mdiarea.background = create_pixmap(QtCore.QSize(100, 100))
sys.exit(app.exec_())

相关内容

  • 没有找到相关文章

最新更新