根据任何图像几何形状调整GraphicView

时间:2019-03-29 12:08:56

标签: python python-3.x pyqt pyqt5 qgraphicsview

我的QGraphicsView应该显示高分辨率的图像。大小应适合可调整大小的窗口。当前,以我想要的方式查看图像,但只能通过为初始视图几何图形提供一些手动调整的值来查看。这看起来不整洁。我还尝试参考此处发布的解决方案:Graphics View and Pixmap Size

我当前的窗口如下:

enter image description here

string

当我尝试确定两点之间的距离时,手动覆盖可能不是一个好主意。即使按比例缩放的距离也给我一个稍微错误的值。

1 个答案:

答案 0 :(得分:2)

我不能使用您的代码,因为有很多隐藏的东西,因此我将提出下一个解决方案,即每次窗口更改大小时,根据场景重新缩放视图。我还实现了一个信号,该信号根据图像的坐标传输图像中的点击信息。

from PyQt5 import QtCore, QtGui, QtWidgets


class ClickableGraphicsView(QtWidgets.QGraphicsView):
    clicked = QtCore.pyqtSignal(QtCore.QPoint)

    def __init__(self, parent=None):
        super(ClickableGraphicsView, self).__init__(parent)
        scene = QtWidgets.QGraphicsScene(self)
        self.setScene(scene)
        self.pixmap_item = None

    def setImage(self, path):
        pixmap = QtGui.QPixmap(path)
        self.pixmap_item = self.scene().addPixmap(pixmap)
        self.pixmap_item.setShapeMode(
            QtWidgets.QGraphicsPixmapItem.BoundingRectShape
        )

    def mousePressEvent(self, event):
        if self.pixmap_item is not None:
            if self.pixmap_item == self.itemAt(event.pos()):
                sp = self.mapToScene(event.pos())
                lp = self.pixmap_item.mapToItem(self.pixmap_item, sp)
                p = lp.toPoint()
                if self.pixmap_item.pixmap().rect().contains(p):
                    self.clicked.emit(p)
        super(ClickableGraphicsView, self).mousePressEvent(event)

    def resizeEvent(self, event):
        self.fitInView(self.sceneRect(), QtCore.Qt.IgnoreAspectRatio)
        super(ClickableGraphicsView, self).resizeEvent(event)


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setWindowTitle("Image Analyzer")
        view = ClickableGraphicsView()
        view.clicked.connect(print)
        view.setImage("image.jpg")

        label = QtWidgets.QLabel("Distance")
        display = QtWidgets.QLCDNumber()

        buttonbox = QtWidgets.QDialogButtonBox(
            QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel
        )

        widget = QtWidgets.QWidget()
        self.setCentralWidget(widget)
        lay = QtWidgets.QGridLayout(widget)
        lay.addWidget(view, 0, 0, 1, 2)
        hlay = QtWidgets.QHBoxLayout()
        hlay.addWidget(label)
        hlay.addWidget(display)
        hlay.addStretch()
        lay.addLayout(hlay, 1, 0)
        lay.addWidget(buttonbox, 1, 1)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())