3

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.

BaCaRoZzo
  • 7,502
  • 6
  • 51
  • 82
Alfael S
  • 31
  • 1
  • 2
  • Use Javascript and extract the filename from the path in the `onAccepted` handler of your `FileDialog`. See the approach used in [this answer](http://stackoverflow.com/a/423385/2538363). – BaCaRoZzo Jun 16 '15 at 15:56
  • 1
    Thanks for the correction of my question, and for your answer! – Alfael S Jun 16 '15 at 17:04
  • 1
    @BaCaRoZzo That's generally speaking a bad idea. – Kuba hasn't forgotten Monica Jun 16 '15 at 18:45
  • @KubaOber well, I totally agree with you! I was just fulfilling the requirement of the OP. Even today, I've used `QFileInfo`. As you said, it's trivial. I should have mentioned it. My fault, sorry. :) – BaCaRoZzo Jun 16 '15 at 19:20

1 Answers1

3

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).

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313