python - QGraphicSscene背景

标签 python pyqt background pyqt5 qgraphicsscene

我正在学习 PyQt5 来开发一个小型学院项目。我需要为 QGraphicScene 设置背景,但我无法使图像很好地融入场景。有时它会重复或太大,具体取决于我应用的比例。这是我的代码:

class MainWindow(QWidget):

    def __init__(self):
        super().__init__()

        self.title = "title";
        self.top = 100
        self.left = 100
        self.width = 1500
        self.height = 900
        self.initUI()

    def initUI(self):

        scene = QGraphicsScene(0, 0, width, heigth)
        view  = QGraphicsView(scene, self)
        image = QImage('pathToImage')
        scene.setBackgroundBrush(QBrush(image))

        self.setWindowTitle(self.title)
        self.setGeometry(self.top, self.left, self.width, self.height)
        self.show()

我尝试使用重新缩放图像

image.scaled(scene.width(), scene.height(), Qt.KeepAspectRatio)

但是不太适合,实际上有滚动条,因为图像太大。 有谁知道问题出在哪里吗?

最佳答案

如果您希望图像缩放,则必须重写 drawBackground() 方法:

class GraphicsScene(QGraphicsScene):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._image = QImage()

    @property
    def image(self):
        return self._image

    @image.setter
    def image(self, img):
        if img != self.image:
            self._image = img
            self.update()

    def drawBackground(self, painter, rect):
        if self.image.isNull():
            super().drawBackground(painter, rect)
        else:
            painter.drawImage(rect, self.image)
scene = GraphicsScene(self)
scene.image = QImage("pathToImage")
view = QGraphicsView(scene)

关于python - QGraphicSscene背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61458100/

相关文章:

python - Ui_MainWindow 没有属性 'show'

java - 如何拥有透明模糊背景的 JFrame

python - 当我想要输入 5 的 'True' 时打印“无”

具有多个标签的 Python Selenium XPATH

python - 为什么 python 不显示在路径图标中?

python - QTextBrowser html链接不可点击

python - TreeView 中的复选框更新缓慢

python - 将数据库中的日期值与日期文字进行比较

java - 从java程序在后台启动shell脚本

当屏幕缩小时,CSS 视频背景不会消失