PyQt - how to detect and close UI if it's already running?

后端 未结 3 763
长情又很酷
长情又很酷 2020-11-30 09:31

I\'m starting the UI from within Maya. If the UI hasn\'t been closed, running the UI again will completely freeze Maya (with the error \"Event Loop is already running\")

3条回答
  •  眼角桃花
    2020-11-30 09:52

    My solution is this:

    import sys
    
    from PyQt5.QtCore import QLockFile
    from PyQt5.QtWidgets import QApplication
    from PyQt5.QtWidgets import QMessageBox
    
    from window import MainWindow
    
    
    if __name__ == "__main__":
        try:
            app_object = QApplication(sys.argv)
            lock_file = QLockFile("app.lock")
    
            if lock_file.tryLock():
                window = MainWindow()
                window.show()
    
                app_object.exec()
            else:
                error_message = QMessageBox()
                error_message.setIcon(QMessageBox.Warning)
                error_message.setWindowTitle("Error")
                error_message.setText("The application is already running!")
                error_message.setStandardButtons(QMessageBox.Ok)
                error_message.exec()
        finally:
            lock_file.unlock()
    

提交回复
热议问题