Reputation: 493
I'm studying Python and PyQt5 in Microsoft Windows 7. My IDE is PyCharm 4.5 CE.
I am trying to make the file dialog to users can select the files or directories easily.
My code is...
# coding: utf-8
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.init_gui()
def init_gui(self):
file_names = QFileDialog.getOpenFileNames(self, "Select one or more files to open", "C:/Windows", "")
print(file_names)
self.setGeometry(100, 100, 500, 300)
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
sys.exit(app.exec_())
This code works properly. But the only thing that annoying me is this.
There are many buttons in parent main window and one of the button shows file dialog.
What is the proper parent in this situation?
Upvotes: 3
Views: 1111
Reputation: 2733
From PyQt5
documentation the method signature is:
QStringList getOpenFileNames (QWidget parent=None, QString caption=QString(), QString directory=QString(), QString filter=QString(), QString selectedFilter=None, Options options=0)
The parent must be an instance of QWidget
or of some class that inherits from QWidget
, and that's exactly what QMainWindow
is (and this explains why everything works as expected).
Now, to understand why PyCharm displays a warning: if you look in the QFileDialog.py
file, which is automatically generated by PyCharm from PyQt5\QtWidgets.pyd
you will see that the method getOpenFileNames
is not declared as staticmethod
nor as classmethod
:
def getOpenFileNames(self, QWidget_parent=None, str_caption='', str_directory='', str_filter='', str_initialFilter='', QFileDialog_Options_options=0): # real signature unknown; restored from __doc__
""" QFileDialog.getOpenFileNames(QWidget parent=None, str caption='', str directory='', str filter='', str initialFilter='', QFileDialog.Options options=0) -> (list-of-str, str) """
pass
so PyCharm expects (wrongly) the method to be called on an instance of QFileDialog
, but here you have no instance of QFileDialog
(as the method docstring suggests the real method signature is unknown), hence it expects the first argument of the method (self
) to be an instance of QFileDialog
and thus it throws a warning.
You can turn off such warning by disabling the inspection just for the desired statement:
# noinspection PyTypeChecker,PyCallByClass
file_names = QFileDialog.getOpenFileNames(self, "Select one or more files to open", "C:/Windows", "")
print(file_names)
Upvotes: 3