Search code examples
pythonpyqt5desktop-applicationpyside2

Restart/Theme Switch Feature for PyQt5 Application


I implemented a theme switch feature, which restarts the application using subprocess and sends a sys variable indicating the desired theme, so that the main controller can know which styles to apply for the application components.

styles_controller.py

def switch_theme(app):
    app.quit()
    if (not dark_mode):
        subprocess.Popen(['python', 'main.py', 'dark'])
    else:
        subprocess.Popen(['python', 'mainp.py', 'light'])

Currently, this implementation works as desired, but my question is, if I create an executable for the application, will this implementation work on both Windows and Linux, will it even work ? What are some better ways to do it ?


Solution

  • When converting the script to executable then it is not necessary to use "python" as a program but the executable itself, also the script is not necessary. So you have to differentiate if it is an executable or a script and in the case of pyinstaller you must use the sys.frozen attribute. Considering the above, the solution is:

    def switch_theme(theme):
        args = [sys.executable]
        if not getattr(sys, "frozen", False):
            args.append("main.py")
        args.append(theme)
        subprocess.Popen(args)
    
    
    def restart():
        QCoreApplication.quit()
        switch_theme("dark" if dark_mode else "light")