我想在QGraphicsView中显示图像,实际上是在QGraphicsScene中,这是简单的部分,bu,当我将光标移到图像上方时,我想看到X和Y坐标线(黄线),就像这样图片,谁能解释我该怎么做?

python - 在QGraphicsView中显示X和Y坐标线-LMLPHP

最佳答案

要实现您想要的,有两个任务:


获取光标的位置,在这种情况下,启用标志mouseTracking,以便在获取位置的位置调用mouseMoveEvent()
在顶层绘画,为此我们使用drawForeground()函数。


from PyQt5 import QtCore, QtGui, QtWidgets


class GraphicsScene(QtWidgets.QGraphicsScene):
    def drawForeground(self, painter, rect):
        super(GraphicsScene, self).drawForeground(painter, rect)
        if not hasattr(self, "cursor_position"):
            return
        painter.save()
        pen = QtGui.QPen(QtGui.QColor("yellow"))
        pen.setWidth(4)
        painter.setPen(pen)
        linex = QtCore.QLineF(
            rect.left(),
            self.cursor_position.y(),
            rect.right(),
            self.cursor_position.y(),
        )
        liney = QtCore.QLineF(
            self.cursor_position.x(),
            rect.top(),
            self.cursor_position.x(),
            rect.bottom(),
        )
        for line in (linex, liney):
            painter.drawLine(line)
        painter.restore()

    def mouseMoveEvent(self, event):
        self.cursor_position = event.scenePos()
        self.update()
        super(GraphicsScene, self).mouseMoveEvent(event)


class GraphicsView(QtWidgets.QGraphicsView):
    def __init__(self, parent=None):
        super(GraphicsView, self).__init__(parent)
        self.setMouseTracking(True)
        scene = GraphicsScene(QtCore.QRectF(-200, -200, 400, 400), self)
        self.setScene(scene)


if __name__ == "__main__":
    import sys
    import random

    app = QtWidgets.QApplication(sys.argv)

    w = GraphicsView()

    for _ in range(4):
        r = QtCore.QRectF(
            *random.sample(range(-200, 200), 2),
            *random.sample(range(50, 150), 2)
        )
        it = w.scene().addRect(r)
        it.setBrush(QtGui.QColor(*random.sample(range(255), 3)))

    w.resize(640, 480)
    w.show()

    sys.exit(app.exec_())


python - 在QGraphicsView中显示X和Y坐标线-LMLPHP

python - 在QGraphicsView中显示X和Y坐标线-LMLPHP

关于python - 在QGraphicsView中显示X和Y坐标线,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56748603/

10-12 18:46