python - 如何将图像添加到 QGraphicsScene 以便矩形项目可以位于其上?

标签 python image pyqt pyqt5 qgraphicsscene

我有一个 python 代码,可以在 QGraphicsScene 上添加多个矩形。

from PyQt5 import QtCore, QtGui, QtWidgets

class GraphicsScene(QtWidgets.QGraphicsScene):
    def __init__(self, parent=None):
        super(GraphicsScene, self).__init__(QtCore.QRectF(-500, -500, 1000, 1000), parent)
        self._start = QtCore.QPointF()
        self._current_rect_item = None

    def mousePressEvent(self, event):
        if self.itemAt(event.scenePos(), QtGui.QTransform()) is None:
            self._current_rect_item = QtWidgets.QGraphicsRectItem()
            self._current_rect_item.setBrush(QtCore.Qt.red)
            self._current_rect_item.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True)
            self.addItem(self._current_rect_item)
            self._start = event.scenePos()
            r = QtCore.QRectF(self._start, self._start)
            self._current_rect_item.setRect(r)
        super(GraphicsScene, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if self._current_rect_item is not None:
            r = QtCore.QRectF(self._start, event.scenePos()).normalized()
            self._current_rect_item.setRect(r)
        super(GraphicsScene, self).mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        self._current_rect_item = None
        super(GraphicsScene, self).mouseReleaseEvent(event)


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        scene =GraphicsScene(self)
        view = QtWidgets.QGraphicsView(scene)
        self.setCentralWidget(view)


if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())

我的问题是如何在 QGraphicsScene(背景)中添加图像,以便矩形覆盖在该图像上?

最佳答案

有几个选项:

  • setBackgroundBrush():

    brush = QtGui.QBrush(QtGui.QPixmap("/path/of/image.png"))
    scene.setBackgroundBrush(brush)
    
  • 重写drawBackground():

    class GraphicsScene(QtWidgets.QGraphicsScene):
        def __init__(self, parent=None):
            super(GraphicsScene, self).__init__(QtCore.QRectF(-500, -500, 1000, 1000), parent)
            self._start = QtCore.QPointF()
            self._current_rect_item = None
    
        def drawBackground(self, painter, rect):
            pixmap = QtGui.QPixmap("/path/of/image.png")
            painter.drawPixmap(QtCore.QPointF(0, 0), pixmap)
    

关于python - 如何将图像添加到 QGraphicsScene 以便矩形项目可以位于其上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67975449/

相关文章:

c# - 如何让 .NET 保存此图像?

python - PyQt5:更新标签?

python - 在 PyQt PushButton 单击期间发送附加变量

python - 另一个类的方法在调用时不能完全工作

python - 调试简单的 Python 价格代码

python - 在不更改原始数据的情况下复制函数内部的数据框

java - ImageJ 叠加 ROI 缩放

java - 确定图像是否具有特定的色谱

python - 如何让用户在 Python 3 中输入数字?

python - 使用 Python 解压缩存档时如何保留符号链接(symbolic link)?