如何在PySide2 GUI中正确嵌入Vispy画布并解决addWidget类型报错
问题根因
- 后端配置错误:显式指定Vispy使用pyglet后端与当前PySide2技术栈不兼容,嵌入Qt GUI必须使用Vispy的Qt适配后端,否则无法生成可用的QWidget组件。
- 控件类型错误:
SceneCanvas本身不是QWidget子类,无法直接传入Qt布局的addWidget方法,需要通过其内置的native属性获取封装完成的Qt控件实例。
修复步骤
- 移除pyglet后端相关配置,删除以下两行代码:
import pyglet vispy.app.use_app('pyglet')
- 修改画布添加到布局的代码,替换为传入
canvas.native:
# 原错误代码 # central_layout.addWidget(canvas, 2,0,1,2, QtCore.Qt.AlignCenter ) # 修改后代码 central_layout.addWidget(canvas.native, 2, 0, 1, 2, QtCore.Qt.AlignCenter)
完整修复后代码
import matplotlib matplotlib.use('Agg') import sys sys.path.append("../../../") import vispy from vispy import color, scene, app from PySide2.QtWidgets import QApplication, QMainWindow, QWidget, QGridLayout, QComboBox, QHBoxLayout, QPushButton, QCheckBox, QLineEdit, QLabel from PySide2 import QtCore if not QApplication.instance(): app = QApplication(sys.argv) else: app = QApplication.instance() mw = QMainWindow() mw.resize(1900,1000) # build canvas canvas = scene.SceneCanvas(keys='interactive', show=False) central_layout = QGridLayout() central_widget = QWidget() central_widget.setLayout(central_layout) mw.setCentralWidget(central_widget) mw.setWindowTitle('Driving Test (2D/3D)') configuration_layout = QHBoxLayout() debug_layout = QHBoxLayout() cmap_attribute = QComboBox() cmap_type = QComboBox() cycle_label = QLabel('Cycle :') debug_mode_checkbox = QCheckBox('Debug Mode') input_cycle = QLineEdit() go_to_specific_cycle_btn = QPushButton('GO') next_cycle_btn = QPushButton('Next Cycle') previous_cycle_btn = QPushButton('Previous Cycle') attribute_selected_info = QLabel() input_cycle.setPlaceholderText('Enter a spécific cycle and click on (GO)') input_cycle.setMaximumWidth(250) go_to_specific_cycle_btn.setMaximumWidth(50) debug_mode_checkbox.setMaximumWidth(100) cycle_label.setFixedSize(80, 40) attribute_selected_info.setFixedSize(500, 40) cmap_attribute.addItems(['snr','power','rcs','velocity', 'range','detection_confidence','elevation']) cmap_type.addItems(['jet','viridis']) configuration_layout.addWidget(cmap_attribute) configuration_layout.addWidget(cmap_type) debug_layout.addWidget(debug_mode_checkbox) debug_layout.addWidget(input_cycle) debug_layout.addWidget(go_to_specific_cycle_btn) debug_layout.addWidget(previous_cycle_btn) debug_layout.addWidget(next_cycle_btn) debug_layout.addWidget(cycle_label) debug_layout.addWidget(attribute_selected_info) central_layout.addLayout(configuration_layout , 0,0,1,2) central_layout.addLayout(debug_layout , 1,0,1,2) central_layout.addWidget(canvas.native, 2,0,1,2 , QtCore.Qt.AlignCenter ) top_grid = canvas.central_widget.add_grid() mw.show() if __name__ == '__main__': import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QApplication.instance().exec_()
修改后运行不会再触发类型错误,对齐参数可正常生效。
内容的提问来源于stack exchange,提问作者B.Sarah
相关产品推荐
相关产品推荐

