0

当我在 Mac OSX 中按 (command + q) 键时,我的 PyQt 应用程序关闭。

(ie) 我的应用程序收到类似于在 windows 中按下 (Alt +F4) 键的关闭事件

但是我怎样才能禁用这种类型的关闭事件,它是 mac 本机关闭键盘快捷键。

以下是我希望我的 qmainwindow 不应该收到关闭事件的示例 pyqt 代码。

#! /usr/bin/python 
import sys 
import os
from PyQt4 import QtGui 
class Notepad(QtGui.QMainWindow):
    def __init__(self):
        super(Notepad, self).__init__()
        self.initUI()
    def initUI(self):
        self.setGeometry(300,300,300,300)
        self.setWindowTitle('Notepad')
        self.show()
        self.raise_()
    #def keyPressEvent(self, keyEvent):
    #    print(keyEvent,'hi')
    #    print('close 0', keyEvent.InputMethod)
    #    if keyEvent.key() != 16777249:
    #        super().keyPressEvent(keyEvent)
    #    else:
    #        print(dir(keyEvent))
    #        return False
    def closeEvent(self, event):
        reply = QtGui.QMessageBox.question(self, 'Message',
            "Are you sure to quit?", QtGui.QMessageBox.Yes | 
            QtGui.QMessageBox.No, QtGui.QMessageBox.No)

        if reply == QtGui.QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()        
def main():
    app = QtGui.QApplication(sys.argv)
    notepad = Notepad()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

???

4

1 回答 1

0

Extend the QtGui.QApplication::events() method to receive this command + q close event and ignore it.

Below is my sample code to achieve it.

def main():
    app = Application()
    notepad = Notepad()
    sys.exit(app.exec_())

class Application(QtGui.QApplication):
    def event(self, event):
        # Ignore command + q close app keyboard shortcut event in mac
        if event.type() == QtCore.QEvent.Close and event.spontaneous():
            if sys.platform.startswith('darwin'):
                event.ignore()
                return False

Thanks everyone

于 2013-08-01T11:33:03.360 回答