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

macOS下Qt应用中mne raw.plot设置block=True仍不阻塞的问题

PySide6 + MNE-Python 绘图阻塞无效问题解决

关于提示的性质

CoreApplication::exec: The event loop is already running 是警告,不是错误。它仅提示Qt事件循环已处于运行状态,不会直接导致程序崩溃,但会干扰raw.plot(block=True)的阻塞逻辑,这也是你遇到绘图窗口打开后直接执行后续打印语句的原因。

问题根源

你的PySide6应用通过app.exec()启动了一个主事件循环,而raw.plot(block=True)内部会尝试再次启动Qt事件循环,两者冲突导致阻塞机制失效,代码直接向下执行。

解决方法

推荐使用MNE内置的qt_exec上下文管理器,它能在已有的Qt事件循环中处理绘图交互,直到窗口关闭才继续执行后续代码,完美适配PySide6的主事件循环场景。

修改后的核心代码

将Show方法中的raw.plot(block=True)替换为:

with mne.utils.qt_exec():
    raw.plot()

完整修改代码

import matplotlib
import mne, sys
from PySide6.QtWidgets import QMainWindow, QPushButton, QApplication

matplotlib.rcParams['font.sans-serif'] = ['Arial Unicode MS']
matplotlib.rcParams['axes.unicode_minus'] = False
matplotlib.use('qtAgg')


class Test(QMainWindow):
    def __init__(self):
        super(Test, self).__init__()
        self.button = QPushButton('Plot raw')
        self.button.clicked.connect(self.Show)
        self.setCentralWidget(self.button)

    def Show(self):
        sample_data_folder = mne.datasets.sample.data_path()
        sample_data_raw_file = (sample_data_folder / 'MEG' / 'sample' /
                                'sample_audvis_filt-0-40_raw.fif')
        raw = mne.io.read_raw_fif(sample_data_raw_file)
        # 使用qt_exec上下文管理器实现阻塞
        with mne.utils.qt_exec():
            raw.plot()
        print('after window close')


app = QApplication(sys.argv)
main = Test()
main.show()
app.exec()
sys.exit()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 05:15:33