如何使用空列表初始化QApplication对象?

huangapple go评论60阅读模式
英文:

How does an empty list work to initialize a QApplication object?

问题

我是新手学习Python和PyQt。当我学习如何使用PyQt5编码时,我看到许多人以这种方式初始化QApplication对象:

app = QtWidgets.QApplication([])

这是合法的,但我该如何理解它呢?

我猜这是因为QApplication()的参数形式为(argc, **argv),所以一个空列表在这里用于进行默认初始化。但我不太了解这个类是如何工作的。
我是否可以只使用QtWidgets.QApplication(sys.argv)来避免麻烦?

英文:

I'm new to python and PyQt. When I studyting how to code with PyQt5, I see many people initialize the QApplication object in such way:

app = QtWidgets.QApplication([])

It's legal, but how do I realize it?

I guess that its because the paraments of QApplication() is like (argc, **argv), so an empty list is useful to make a default initialization. But I dont really know how the class works.
May I just use QtWidgets.QApplication(sys.argv) to avoid any trouble?

答案1

得分: 1

QApplication接受一个列表作为位置参数,所以如果没有这个列表,它将无法工作。该列表可以包含额外的指令,例如[-style, fusion],但是QApplication可以在没有额外指令(空列表)的情况下正常运行。

正确初始化QApplication的方式是:

app = QApplication(sys.argv)

这样,用于启动程序的任何参数都会传递给QApplication。

你看到的空列表可能是因为人们提供了一个最小可重现示例。当手头的问题与QApplication的参数无关时,可以使用空列表。

英文:

QAplication takes a list as a positional argument, so it won't work without it. That list can contain additional instructions like [-style, fusion], but QApplication will run fine without additional instructions (empty list).

The 'proper' way to initialise QApplication is:

app = QApplication(sys.argv)

That way any arguments that were used to start the program are passed on to QApplication.

The empty list you're seeing is probably from people providing a Minimal, Reproducible Example. When the problem at hand doesn't have anything to do with arguments for QApplication, you can just use an empty list.

huangapple
  • 本文由 发表于 2023年5月11日 14:25:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76224700.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定