Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

python - How to import from Qt:: namespase (Qt5, Python3.x)?

For my application, I need to set some widget parameters like alignment (Qt::AlignBottom) and others. But I can't import them (other PyQt5 stuff imports without any issues).

Using this code

from PyQt5 import Qt

progressBar = QProgressBar(splash)
progressBar.setAlignment(Qt.AlignBottom)

I got the following error:

Traceback (most recent call last):
  File "run_app.py", line 50, in <module>
    runSemApp(sys.argv)
  File "run_app.py", line 32, in runSemApp
    progressBar.setAlignment(Qt.AlignBottom)
AttributeError: 'module' object has no attribute 'AlignBottom'

And using this one works:

from PyQt5.Qt import *

progressBar = QProgressBar(splash)
progressBar.setAlignment(Qt.AlignBottom)

Though I have a working solution, I would like to import only Qt.AlignBottom and not *. Also, why doesn't Qt.AlignBottom work with from PyQt5 import Qt?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think the confusion here is that PyQt has a special virtual module called Qt, which imports everything into a single namespace. This is a quite useful feature, but it's a real shame that the name clash with QtCore.Qt wasn't avoided.

In the first example, the error can be "fixed" by using the somewhat weird-looking Qt.Qt.AlignBottom. But obviously, explicitly importing from QtCore is a much better solution. It's also worth noting that the PyQt5 package is a lazy loader, so import PyQt5 will just import an empty namespace with no access to the other modules.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...