How to get the current QApplication in pyQt?

独自空忆成欢 提交于 2021-01-27 06:42:27

问题


I am trying to get a reference to the current QApplication object with pyQt5, but couldn't find the function. My search about "pyQt get current QApplication" shows results about how to create an QApplication. So my question is:

Is there a global QApplication object, and if so how can get a reference to an existing (the current) application.

The reason I ask, is that I want to test if a debugging code is running within a Qt GUI application. Then, I'd like to bring up a QMessagebox to show error messages if the function is used in a Qt application; or print out a message to stdout otherwise.


回答1:


there should only be one QApplication, and if we want to obtain the existing one, you must use instance(), a common approach is to use the following technique:

app = QtWidgets.QApplication.instance()
if app is None:
    # if it does not exist then a QApplication is created
    app = QtWidgets.QApplication([])


来源:https://stackoverflow.com/questions/53387733/how-to-get-the-current-qapplication-in-pyqt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!