【问题标题】:How to add a pixmap drawn in QGraphicsItem to QGraphicsScene? [duplicate]如何将QGraphicsItem中绘制的像素图添加到QGraphicsScene? [复制]
【发布时间】:2018-04-16 10:02:10
【问题描述】:

下例中如何将QGraphicsItem中绘制的像素图添加到QGraphicsScene中?

#!/usr/bin/env python

from PyQt5.QtCore import QRectF, Qt
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QGraphicsItem, QGraphicsView, QGraphicsScene, QMainWindow

class TicTacToe(QGraphicsItem):
    def __init__(self, helper):
        super(TicTacToe, self).__init__()

        self.mypixmap = QPixmap("exit.png")

    def paint(self, painter, option, widget):
        painter.setOpacity(1)
        painter.drawPixmap(0,0, 300, 300, self.mypixmap)


    def boundingRect(self):
        return QRectF(0,0,300,300)


class MyGraphicsView(QGraphicsView):
    def __init__(self):
        super(MyGraphicsView, self).__init__()
        scene = QGraphicsScene(self)

        self.tic_tac_toe = TicTacToe(self)

        scene.addItem(self.tic_tac_toe)

        self.setScene(scene)

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)


class Example(QMainWindow):    
    def __init__(self):
        super(Example, self).__init__()

        self.y = MyGraphicsView()
        self.setCentralWidget(self.y)

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    w = Example()
    w.show()
    sys.exit(app.exec_())

【问题讨论】:

  • 抱歉,我不清楚这个问题。你的代码有什么问题?您要达到的目标是什么?你能告诉我们更多细节吗?
  • 我需要用画家在像素图上绘制,缩放图片,并为其添加滚动条。这就是目的。 @S.Monteleone
  • @Aquarius_Girl。你为什么不使用QGraphicsPixmapItem
  • @ekhumoro 如果我使用 qgraphicspixmapitem 那么我可以在场景中包含绘制的像素图吗?
  • @Aquarius_Girl。你不需要画任何东西——它会为你做所有的事情。

标签: python qt pyqt qpixmap


【解决方案1】:

试试看:

拖放图像, 放大图片-> Qt.Key_Right, 缩小图像

from PyQt5.QtCore    import (QLineF, QPointF, QRectF, 
                             pyqtSignal, QStandardPaths, Qt)
from PyQt5.QtGui     import (QIcon, QBrush, QColor, QPainter, QPixmap)
from PyQt5.QtWidgets import (QAction, QMainWindow, QApplication, 
                             QGraphicsObject,
                             QGraphicsView, QGraphicsScene, QGraphicsItem,
                             QGridLayout, QVBoxLayout, QHBoxLayout, 
                             QFileDialog, QLabel, QLineEdit, QPushButton)
from PyQt5.QtOpenGL  import QGLFormat 

class MyGraphicsView(QGraphicsView):
    backgroundColor = QColor(28, 31, 34)     # Background color
    def __init__(self):
        super(MyGraphicsView, self).__init__()

        self.resize(800, 600)
        self.setBackgroundBrush(self.backgroundColor)
        self.setCacheMode(self.CacheBackground)
        self.setRenderHints(
            QPainter.Antialiasing | QPainter.TextAntialiasing | QPainter.SmoothPixmapTransform)
        if QGLFormat.hasOpenGL():
            self.setRenderHint(QPainter.HighQualityAntialiasing)
        self.setViewportUpdateMode(self.SmartViewportUpdate)
        self._scene = QGraphicsScene(-400, -300, 800, 600, self)
        self.setScene(self._scene)            
        self._itemImage = None

    def keyReleaseEvent(self, event):
        """ Button processing event """
        self._scaleImage(event)
        super(MyGraphicsView, self).keyReleaseEvent(event)

    def closeEvent(self, event):
        """ Clear all items in the scene when the window is `closed` """
        self._scene.clear()
        self._itemImage = None
        super(MyGraphicsView, self).closeEvent(event)

    def _scaleImage(self, event):
        """ Image zoom operation """
        if not self._itemImage:
            return
        scale = self._itemImage.scale()
        if event.key() == Qt.Key_Right:             
            # Enlarge Image -> Qt.Key_Right 
            if scale >= 0.91:
                return
            self._itemImage.setScale(scale + 0.1)
        elif event.key() == Qt.Key_Left:            
            # Reduce image <- Qt.Key_Left
            if scale <= 0.11:
                return
            self._itemImage.setScale(scale - 0.1)


    def loadImage(self):
        path, _ = QFileDialog.getOpenFileName(
            self, 'Please select an image', 
            QStandardPaths.writableLocation(QStandardPaths.DesktopLocation), 
            'Image(*.jpg *.png)')
        if not path:
            return
        if self._itemImage:
            # Delete previous item
            self._scene.removeItem(self._itemImage)
            del self._itemImage
        self._itemImage = self._scene.addPixmap(QPixmap(path))
        self._itemImage.setFlag(QGraphicsItem.ItemIsMovable)
        self._itemImage.setScale(0.1)         # Default load factor

        size = self._itemImage.pixmap().size()
        # Adjust the image in the middle
        self._itemImage.setPos(
            -size.width() * self._itemImage.scale() / 2,
            -size.height() * self._itemImage.scale() / 2
        )        


if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)

    w   = MyGraphicsView()
    w.show()
    ww = QPushButton('Select a file', clicked=w.loadImage)
    ww.show()    

    sys.exit(app.exec_())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-27
    • 2011-02-17
    相关资源
    最近更新 更多