Error "Widget: Must construct a QApplication before a QWidget"

Dear all, I am a beginner in Python, full of enthusiam, but facing plenty of errors. I do not understand why I receive this message “Widget: Must construct a QApplication before a QWidget” with the code below ? There is not even the opening of the window to select the folder.

my_dir = QFileDialog.getExistingDirectory(
    None,
    "Open a folder",
    RootFolder_AuBCI + '/data/FIF/',
    QFileDialog.ShowDirsOnly
    )

This is unrelated to Python. PyQt is a wrapper around the Qt framework and “Must construct a QApplication before a QWidget” is one of the framework rules. The framework can only serve your program when you have created an instance of QApplication.

Creating a program with a GUI frontend is generally not a no-brain operation. It may help you a lot to do a tutorial first. This page on the Python wiki has a list of resources to learn PyQt. May help you a lot.

1 Like

Thanks, indeed the page on Python wiki helped, even if I am not able to understand all concepts at this stage, simply importing “QApplication” and creating it helped to solve the issue.

from PyQt5.QtWidgets import QFileDialog, QApplication, QWidget, QPushButton, QVBoxLayout

app = QApplication([])

my_dir = QFileDialog.getExistingDirectory(
    None,
    "Open a folder",
   RootFolder_AuBCI + '/data/FIF/',
    QFileDialog.ShowDirsOnly
    )