如何获取当前的QApplication? [英] How to get the current QApplication?

查看:85
本文介绍了如何获取当前的QApplication?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 pyQt5 获取对当前 QApplication 对象的引用,但找不到该函数.我对pyQt get current QApplication"的搜索显示了有关如何创建 QApplication 的结果.所以我的问题是:

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:

是否有全局 QApplication 对象,如果有,如何获取对现有(当前)应用程序的引用.

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

我问的原因是我想测试调试代码是否在 Qt GUI 应用程序中运行.然后,如果在 Qt 应用程序中使用该函数,我想调出一个 QMessagebox 来显示错误消息;或者打印一条消息到标准输出.

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.

推荐答案

QApplication 应该只有一个,如果我们要获取现有的,必须使用instance(),一个常见的方法是使用以下技术:

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([])

这篇关于如何获取当前的QApplication?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆