Reputation: 1
I want to create a GUI for data elaboration. It requires the directory path where files are located and additional parameters for elaborating them.
I would like to set a two level control, so that the user is informed if they haven't selected the directory. If they have, an error message must be raised if a non-numeric parameter is provided:
Here is the code:
class Window(QtWidgets.QMainWindow, gui.Ui_myGUI):
def __init__(self, parent = None):
super(Window, self).__init__(parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.GetDirectory)
self.pushButton_2.clicked.connect(self.ValidateInput)
self.show()
def GetDirectory(self):
self.response = QFileDialog.getExistingDirectory(self, caption = 'Select a folder')
os.chdir(self.response)
def ValidateInput(self):
if hasattr(Window, "response"):
exp = str(self.lineEdit.text())
if exp.isnumeric():
self.Process()
else:
msg = QMessageBox()
msg.setIcon(QMessageBox.Warning)
msg.setWindowTitle("Warning")
msg.setText('Numeric data required')
msg.exec_()
else:
msg = QMessageBox()
msg.setIcon(QMessageBox.Warning)
msg.setWindowTitle("Warning")
msg.setText('You need to select a folder')
msg.exec_()
Process is the method for the actual data elaboration.
This works fine if the folder is not selected, but it just doesn't if the directory path is selected after the first error message came out.
In fact in this case, even though I got the folder right, I still get the first message box, telling me I need to select a folder.
I guess a trivial solution would be to define one method for both acquiring directory path and validating input data (and eventually starting elaboration), but I would rather keep them separated and linked to 2 different buttons.
Upvotes: 0
Views: 34
Reputation: 244132
The problem is that Window does not have the "response" attribute but an instance of the Window class has that attribute. Window does not have the dynamic attributes. So in your case you should change to:
if hasattr(self, "response"):
Even in these cases I prefer to use a default value for example None and then use that value to know if the directory has already been chosen, something like:
class Window(QtWidgets.QMainWindow, gui.Ui_myGUI):
def __init__(self, parent = None):
super(Window, self).__init__(parent)
self.directory = None
self.setupUi(self)
self.pushButton.clicked.connect(self.get_directory)
self.pushButton_2.clicked.connect(self.validate_input)
self.show()
def get_directory(self):
directory = QFileDialog.getExistingDirectory(self, caption = 'Select a folder')
if directory:
self.directory = directory
os.chdir(self.directory)
def validate_input(self):
message = ""
if self.directory is not None:
exp = self.lineEdit.text()
if exp.isnumeric():
self.Process()
else:
message = "Numeric data required"
else:
message = "You need to select a folder"
if message:
msg = QMessageBox()
msg.setIcon(QMessageBox.Warning)
msg.setWindowTitle("Warning")
msg.setText(message)
msg.exec_()
Upvotes: 1