![](/img/trans.png)
[英]How to re-scale vertices to fit within certain range while preserving aspect ratio?
[英]How to scale a QPixmap preserving aspect and centering the image?
我想在 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_())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.