在pyQt4中的图片上涂上涂鸦

时间:2018-11-14 18:17:48

标签: python pyqt4

假设我要加载图像并在其上涂抹。但是,如果图像较大,则无法放入图像查看器。因此,我想要一个滚动条。我该怎么做?

例如:假设图片是:

enter image description here

当我将其加载到程序中时,它变为:

enter image description here

现在,我想将其放入滚动条小部件中(以便可以完全访问图像),最重要的是我想在其上进行任何形式的绘制(涂抹)。如何使用PyQt4执行此操作?有没有可用的python代码?

1 个答案:

答案 0 :(得分:1)

如果要使用QScrollbar放置图像,则可以使用QScrollArea,但是如果您要绘制正确的图像,则可以使用QGraphicsView,因为允许您添加项目。例如,要进行涂鸦,可以使用QGraphicsPathItem并为图像QGraphicsPixmapItem使用,如下所示:

from PyQt4 import QtCore, QtGui

class ScribbleView(QtGui.QGraphicsView):
    def __init__(self, parent=None):
        super(ScribbleView, self).__init__(parent)
        self.setScene(QtGui.QGraphicsScene(self))
        self._image_item = QtGui.QGraphicsPixmapItem()
        self.scene().addItem(self._image_item)
        self.initial_path()

    def initial_path(self):
        self._path = QtGui.QPainterPath()
        pen = QtGui.QPen(QtGui.QColor("green"), 4, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap)
        self._path_item = self.scene().addPath(self._path, pen)

    @QtCore.pyqtSlot()
    def load_image(self):
        filename = QtGui.QFileDialog.getOpenFileName(self, 
            "Open Image", QtCore.QDir.currentPath(), 
            "Image Files (*.png *.jpg *.bmp)")
        if filename:
            self._image_item.setPixmap(QtGui.QPixmap(filename))

    def mousePressEvent(self, event):
        if not self._image_item.pixmap().isNull():
            self._path.moveTo(self.mapToScene(event.pos()))
            self._path_item.setPath(self._path)
        super(ScribbleView, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if not self._image_item.pixmap().isNull():
            self._path.lineTo(self.mapToScene(event.pos()))
            self._path_item.setPath(self._path)
        super(ScribbleView, self).mousePressEvent(event)

    def mouseReleaseEvent(self, event):
        if not self._image_item.pixmap().isNull():
            self._path.lineTo(self.mapToScene(event.pos()))
            self._path_item.setPath(self._path)       
            self.initial_path()
        super(ScribbleView, self).mouseReleaseEvent(event)

class ScribbleWidget(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(ScribbleWidget, self).__init__(parent)
        view = ScribbleView()
        self.setCentralWidget(view)
        menubar = self.menuBar()
        file_menu = menubar.addMenu("&File")
        image_action = file_menu.addAction("Load Image")
        image_action.triggered.connect(view.load_image)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    w = ScribbleWidget()
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())

enter image description here