首页 > 解决方案 > 关闭 QMainWindow 的 QAction 仅在 IPython 中行为不一致

问题描述

我想要一个用户可以通过以下方式关闭的 QMainWindow:单击窗口关闭按钮、单击菜单中的项目或使用键盘快捷键。这是我的解决方案:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import (QAction, qApp, QApplication, QMainWindow)

class Window(QMainWindow):
    '''A simple window'''

    def __init__(self):
        super().__init__()
        self.make_gui()

    def make_gui(self):
        '''Create main GUI window'''
        self.menuBar()
        self.statusBar()
        exitAction = QAction(QIcon(None), 'Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(qApp.quit)
        fileMenu = self.menuBar().addMenu('Actions')
        fileMenu.addAction(exitAction)
        self.show()


if __name__ == '__main__':
    APP = QApplication([])
    GUI1 = Window()
    sys.exit(APP.exec_())

当我用 python 运行这段代码时,这每次都有效,无论三个动作中的哪一个用于关闭窗口。当我在 IPython 中运行它时,可能会发生以下行为之一:

  1. 一切都按预期工作。

  2. 退出时,窗口不会关闭。

  3. 退出时,窗口不会关闭,IPython 会退出。

  4. 启动时,IPython shell 中开始出现警告。与应用程序交互时会出现更多。在这些警告首次出现后,它们将出现在每次后续启动中,直到 IPython 重新启动。

警告示例:

QWindowsContext::windowsProc: No Qt Window found for event 0x1c (WM_ACTIVATEAPP), hwnd=0x0xb0dd8.
QWindowsContext::windowsProc: No Qt Window found for event 0x2a3 (WM_MOUSELEAVE), hwnd=0x0xb0dd8.
QWindowsContext::windowsProc: No Qt Window found for event 0x24a (WM_POINTERLEAVE), hwnd=0x0xb0dd8.
QWindowsContext::windowsProc: No Qt Window found for event 0x1c (WM_ACTIVATEAPP), hwnd=0x0xb0dd8.

我的环境:Windows 10 上的 Python 3.7.2 64 位。

标签: pythonpython-3.xpyqtipythonpyqt5

解决方案


推荐阅读