2014-02-27 64 views
1

我想要在用戶註銷或關閉應用程序時處理,但由於我的應用程序在MainWindow關閉時將其最小化到托盤,我遇到了麻煩。當我註銷時,會調用closeEvent,但我無法確定它是否來自嘗試退出的操作系統或按下'x'(關閉)按鈕的用戶。如何處理來自closeEvent的PyQt4的檢測註銷/關閉?

只有當它是操作系統,我想關閉我的連接,並實際終止應用程序。不幸的是,closeEvent在任何其他函數之前被調用。在下面的示例中,僅當您註釋掉event.ignore()時,纔會調用commitDataaboutToQuit

任何幫助,將不勝感激:)

http://pyqt.sourceforge.net/Docs/PyQt4/qapplication.html#commitData

http://pyqt.sourceforge.net/Docs/PyQt4/qcoreapplication.html#aboutToQuit

http://qt-project.org/doc/qt-4.8/qapplication.html#details

import sys 
from PyQt4 import QtGui 


class myWidget(QtGui.QWidget): 
    def closeEvent(self, event): 
     print "CLOSING" 
     event.ignore() 


class myApp(QtGui.QApplication): 
    def __init__(self, argv): 
     QtGui.QApplication.__init__(self, argv) 
     print "CREATED" 

    def commitData(self, session_manager): 
     print "COMMITTING" 


def cd(session_manager): 
    print "ALSO CMOMMITTING" 


def about_to_quit(): 
    print "QUITTING" 


def main(): 
    app = myApp(sys.argv) 
    app.aboutToQuit.connect(about_to_quit) 
    w = myWidget() 
    w.resize(250, 150) 
    w.setWindowTitle('Simple') 
    w.show() 
    sys.exit(app.exec_()) 

if __name__ == '__main__': 
    main() 

回答