简体   繁体   中英

QPixmap: How to increase the size of the picture in addPixmap?

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

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

        scene.addPixmap(self.m)

        self.setScene(scene)
        self.setCacheMode(QGraphicsView.CacheBackground)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)

The png is already there. What is the way to increase its size while showing it on the screen in scrollbars?

Aim is to have a button on whose click the size of this picture should increase.

You have to use setScale() . Also when you use addPixmap() this returns the created QGraphicsPixmapItem .

In addition, the scaling is a transformation so it has a transformation origin, by default it is (0, 0) , but in this case a better option would be to place it in the center of the image.

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class MyGraphicsView(QGraphicsView):
    def __init__(self):
        super(MyGraphicsView, self).__init__()
        scene = QGraphicsScene(self)
        self.m = QPixmap("exit.png")
        self.item = scene.addPixmap(self.m)

        self.item.setTransformOriginPoint(self.item.boundingRect().center())

        self.setScene(scene)
        self.setCacheMode(QGraphicsView.CacheBackground)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)

    @pyqtSlot()
    def scale_pixmap(self):
        self.item.setScale(2*self.item.scale())

class Example(QMainWindow):
    def __init__(self):
        super(Example, self).__init__()
        centralWidget = QWidget()
        self.setCentralWidget(centralWidget)
        lay = QVBoxLayout(centralWidget)
        gv = MyGraphicsView()
        button = QPushButton("scale")
        lay.addWidget(gv)
        lay.addWidget(button)
        button.clicked.connect(gv.scale_pixmap)


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM