How can I extract the filename of a path

3.4k Views Asked by At

As stated in the title, I would like to extract the filename of a path (I use FileDialog to find a file). If possible without using c++ code.

I'm on Qt 5.4.2 mingw. Thank you in advance.

1

There are 1 best solutions below

0
On

Given how trivial it is to interface QML with any C++ class, it's not a problem that the solution is in C++.

QFileInfo(filePath).fileName() does it, if filePath is the path returned from the file dialog. You only need to expose it to QML:

class Helper : public QObject
{
  Q_OBJECT
public:
  Q_INVOKABLE QString fileNameFromPath(const QString & filePath) const {
    return QFileInfo(filePath).fileName();
  }  
};

int main(int argc, char *argv[]) {
    QGuiApplication app(argc, argv);
    QQuickView view;

    Helper helper;
    view.rootContext()->setContextProperty("appHelper", &helper);

    view.setSource(QUrl::fromLocalFile("foo.qml"));
    view.show();

    return app.exec();
}

From QML, simply invoke appHelper.fileNameFromPath(path).