You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在pyqtgraph中获取GLViewWidget的当前相机参数

解决方案

核心参数获取方式

pyqtgraph的GLViewWidget所有相机参数都存储在实例的opts字典中,无需额外调用接口,直接读取对应字段即可:

  • 方位角(azim):w.opts['azimuth'],对应orbit方法的第一个参数
  • 俯仰角(elev):w.opts['elevation'],对应orbit方法的第二个参数
  • 平移参数(dx/dy/dz):w.opts['center'],是QVector3D类型,三个分量分别为w.opts['center'].x()、w.opts['center'].y()、w.opts['center'].z(),对应pan方法的三个平移参数

实现视角保存/复用的完整示例

下面的代码添加了快捷键支持:按S键保存当前视角到本地文件,下次启动自动读取加载视角:

import sys
import json
import pyqtgraph as pg
import pyqtgraph.opengl as gl
from PyQt5 import QtCore, QtGui
from pyqtgraph.Qt import QtWidgets

# 视角保存路径
VIEW_CONFIG_PATH = "view_config.json"

def save_view(w):
    config = {
        "azimuth": w.opts['azimuth'],
        "elevation": w.opts['elevation'],
        "center_x": w.opts['center'].x(),
        "center_y": w.opts['center'].y(),
        "center_z": w.opts['center'].z()
    }
    with open(VIEW_CONFIG_PATH, "w", encoding="utf-8") as f:
        json.dump(config, f, indent=2)
    print("视角已保存")

def load_view(w):
    try:
        with open(VIEW_CONFIG_PATH, "r", encoding="utf-8") as f:
            config = json.load(f)
        w.setCameraPosition(
            azimuth=config['azimuth'],
            elevation=config['elevation'],
            pos=QtGui.QVector3D(config['center_x'], config['center_y'], config['center_z'])
        )
        print("视角已加载")
    except FileNotFoundError:
        print("未找到历史视角配置,使用默认视角")

# 快捷键事件处理
class KeyPressFilter(QtCore.QObject):
    def __init__(self, w):
        super().__init__()
        self.w = w
    def eventFilter(self, obj, event):
        if event.type() == QtCore.QEvent.KeyPress and event.key() == QtCore.Qt.Key_S:
            save_view(self.w)
            return True
        return super().eventFilter(obj, event)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    w = gl.GLViewWidget()
    # 安装快捷键过滤器
    key_filter = KeyPressFilter(w)
    w.installEventFilter(key_filter)
    # 加载历史视角
    load_view(w)
    
    g = gl.GLGridItem(size=QtGui.QVector3D(100,100,1),color=(255, 255, 0, 100))
    w.addItem(g)
    w.show()
    sys.exit(app.exec())

补充说明

  • 除了直接读取opts字段,也可以调用w.cameraPosition()方法直接获取当前相机的坐标、方位角、俯仰角参数
  • 视角恢复也可以分开调用orbit和pan方法实现,和直接调用setCameraPosition效果一致

内容的提问来源于stack exchange,提问作者Kong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 11:24:02