Command line interface

Adds the ability to specify which file to open from the command line to our text editor.

Introduction

We now have a working text editor that can open and save files. We might, however, want to extend its utility by enabling users to more quickly and efficiently use it to edit files. In this tutorial we will make the editor act more like a desktop application by enabling it to open files from command line arguments or even using Open with from within Dolphin.

Code and Explanation

mainwindow.h

Here we have done nothing but add a new openFileFromUrl() function which takes a QUrl. Again, we use URLs instead of strings so that we can also work with remote files as if they were local.

mainwindow.cpp

There's no new code here, only rearranging. Everything from void openFile() has been moved into void openFileFromUrl(const QUrl &inputFileName) except the call to QFileDialog::getOpenFileUrl().

This way, we can call openFile() if we want to display a dialog, or we can call openFileFromUrl(const QUrl &) if we know the name of the file already. Which will be the case when we feed the file name through the command line.

main.cpp

This is where all the QCommandLineParser magic happens. In previous examples, we only used the class to feed QApplication the necessary data for using flags like --version or --author. Now we actually get to use it to process command line arguments.

First, we tell QCommandLineParser that we want to add a new positional argument. In a nutshell, these are arguments that are not options. -h or --version are options, file is an argument.

Later on, we start processing positional arguments, but only if there is one. Otherwise, we proceed as usual. In our case we can only open one file at a time, so only the first file is of interest to us. We call the openFileFromUrl() function and feed it the URL of the file we want to open, whether it is a local file like "$HOME/foo" or a remote one like "ftp.mydomain.com/bar". We use the overloaded form of QUrl::fromUserInput() in order to set the current path. This is needed in order to work with relative paths like "../baz".

CMakeLists.txt

We don't need to change anything in here.

Running our application

Again, you can repeat the same steps provided in {{< ref "hello_world#kxmlgui-running" >}} to build and install the application.

However, we will test if our application handles files from the command line correctly. Create a simple file:

Now you may pass it as argument with:

or

You should then see your application run and load testfile.txt directly from its UI, showing "It works!" in your textArea.

Last updated