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

例如:假设图像为:



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



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

最佳答案

如果要使用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_())


python - 在pyQt4中的图片上涂上涂鸦-LMLPHP

10-07 22:53