QGraphicsView 显示图片

本文介绍了如何在PyQt6环境中利用QGraphicsView、QGraphicsScene和QtGui.QPixmap显示图片,包括设置图片尺寸、位置以及显示多张图片的方法。

QGraphicsView 显示图片

QGraphicsView 是 PyQt6 里负责显示图形的组件,搭配 QGraphicsScene 和 QtGui.QPixmap() 就可以显示图片,这篇教学会介绍如何在 PyQt6 窗口里加入 QGraphicsView 组件并显示图片。

快速预览:

  • QGraphicsView 显示图片

  • 改变图片尺寸

  • 设定图片位置

  • 显示多张图片

QGraphicsView 显示图片

建立 PyQt6 窗口物件后,透过 QtWidgets.QGraphicsView(widget)方法,就能在指定的组件中建立显示图形组件,QGraphicsView 建立后,需再使用 QtWidgets.QGraphicsScene()建立场景组件,再透过QtGui.QPixmap()于场景中加入图片,最后将场景加入 QGraphicsView 就可以显示图片,如果场景大小超过显示区域,会自动出现卷轴。

 from PyQt6 import QtWidgets, QtGui
 import sys
 app = QtWidgets.QApplication(sys.argv)
 ​
 Form = QtWidgets.QWidget()
 Form.setWindowTitle('千牛编程思维')
 Form.resize(300, 300)
 ​
 grview = QtWidgets.QGraphicsView(Form)  # 加入 QGraphicsView
 grview.setGeometry(20, 20, 260, 200)    # 设定 QGraphicsView 位置与大小
 scene = QtWidgets.QGraphicsScene()      # 加入 QGraphicsScene
 scene.setSceneRect(0, 0, 300, 400)      # 设定 QGraphicsScene 位置与大小
 img = QtGui.QPixmap('mona.jpg')         # 加入图片
 scene.addPixmap(img)                    # 將图片加入 scene
 grview.setScene(scene)                  # 设定 QGraphicsView 的场景為 scene
 ​
 Form.show()
 sys.exit(app.exec())

class 写法:

 from PyQt6 import QtWidgets, QtGui
 import sys
 ​
 class MyWidget(QtWidgets.QWidget):
     def __init__(self):
         super().__init__()
         self.setWindowTitle('千牛编程思维')
         self.resize(300, 300)
         self.ui()
 ​
     def ui(self):
         self.grview = QtWidgets.QGraphicsView(self)  # 加入 QGraphicsView
         self.grview.setGeometry(20, 20, 260, 200)    # 设定 QGraphicsView 位置与大小
         scene = QtWidgets.QGraphicsScene()           # 加入 QGraphicsScene
         scene.setSceneRect(0, 0, 300, 400)           # 设定 QGraphicsScene 位置与大小
         img = QtGui.QPixmap('mona.jpg')              # 加入图片
         scene.addPixmap(img)         &nb
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值