【问题标题】:Show X and Y coordinates lines in QGraphicsView在 QGraphicsView 中显示 X 和 Y 坐标线
【发布时间】:2019-11-06 23:18:03
【问题描述】:

我想在 QGraphicsView 中显示图像,实际上是在 QGraphicsScene 中,这是最简单的部分,但是,当我将光标移到图像上时,我想看到 X 和 Y 坐标线(黄线),就像在这张图片中一样,谁能解释我如何做到这一点?

【问题讨论】:

    标签: python pyqt pyqt5 qgraphicsview qgraphicsscene


    【解决方案1】:

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

    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_())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-24
      • 1970-01-01
      • 2021-10-05
      • 2016-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多