No name 'QApplication' in module 'PyQt5.QtWidgets' error in Pylint
Solution 1:
I've figured out the issue, apparently Pylint doesn't load any C extensions by default, because those can run arbitrary code.
So I found that if you create a system file in your project directory with the file named .pylintrc
the rc file can whitelist this package to stop throwing errors by adding the following code in the rc file extension-pkg-whitelist=PyQt5
. So essentially the issue isn't PyQt5, it was the linter throwing false errors due to this.
Solution 2:
I think the simplest way to remove package import errors is by going into vscode's JSON settings by Ctrl+Shift+P, search "settings" and choose Preferences: Open Settings (JSON)
and adding this line to the dict:
"python.linting.pylintArgs": ["--extension-pkg-whitelist=PyQt5"]
If you want to add multiple packages, just add it with the first, separated by a comma like this:
"python.linting.pylintArgs": ["--extension-pkg-whitelist=PyQt5,otherPkg"]
Solution 3:
I found a solution easy, just use QApplication this way:
my_app = QtWidgets.QApplication(sys.argv)
and do not import QApplication
from PyQt5
.
Tested in PyQt5!
Solution 4:
I can reproduce the PyLint errors in Visual Studio Code on Windows 10 (Python 3.7.3, PyQt 5.11.3, PyLint 2.3.1). Though it doesn't prevent me from running the code, as the question suggests.
It is certainly a problem with the linter, not the PyQt5 installation or anything else, as PyLint stops complaining when changing the code to the following equivalent:
from PyQt5 import QtWidgets
app = QtWidgets.QApplication([])
window = QtWidgets.QWidget()
window.setWindowTitle("Test")
window.show()
app.exec_()
The notable difference being that this code imports the QtWidgets
module as a whole, not individual class objects defined in it.
Solution 5:
If you use VSCode, go to "File" > "References" > "Settings" > click on this icon in top-left corner: (The "settings.json" file will be opened) > add these lines to "settings.json":
{
"python.linting.pylintArgs": [
"--extension-pkg-whitelist=PyQt5"
]
}