Skip to content

Instantly share code, notes, and snippets.

@ericoporto
Created June 17, 2016 23:22
Show Gist options
  • Save ericoporto/9b8651124f7efacca7d3f22d0391984e to your computer and use it in GitHub Desktop.
Save ericoporto/9b8651124f7efacca7d3f22d0391984e to your computer and use it in GitHub Desktop.
How to open a file from Nautilus (in Ubuntu) with your PyQt app

I created a file mymime.xml

<?xml version='1.0' encoding='utf-8'?>
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
    <mime-type type="text/myapp">
        <comment>my format</comment>
        <glob pattern="*.myformat"/>
    </mime-type>
</mime-info>

and a file myapp.desktop

[Desktop Entry]
Name=MyApp
GenericName=My Generic Name 
Comment=a comment
Exec=myapp
Icon=myicon
Terminal=false
Type=Application
Categories=Development;
MimeType=text/myapp;
Name[en_US]=MyApp

Now when I right click on a file that has myformat ending, it suggests opening with MyApp, which is the behavior I was looking!

We need to make the PyQt code work with the argument it will receive.

class MainWindow(QMainWindow):
    def __init__(self, filelist, **kwargs):

        openFileAtStart(filelist)

    def openFileAtStart(self, filelist):
        matching = [s for s in filelist if ".myformat" in s]
        if len(matching) > 0:
            self.openFileByName(matching)

if __name__ == "__main__":
    from sys import argv, exit
    from PyQt5.QtWidgets import QApplication
    a = QApplication(argv)
    MainWindow(argv)

Basically, at opening, QApplication needs to read the argv arguments, and removes anything related to Qt. Than I pass the remaining arguments to my application ("MainWindow"), which will handle the list checking for items that match my format and will throw this list to my function that handles opening files.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment