2015-06-16 130 views
1

如標題所述,我想提取路徑的文件名(我使用FileDialog來查找文件)。如果可能,不使用C++代碼。如何提取路徑的文件名

我在Qt 5.4.2 mingw。先謝謝你。

+0

使用Javascript並從'FileDialog'的'onAccepted'處理程序的路徑中提取文件名。請參閱[本答案](http://stackoverflow.com/a/423385/2538363)中使用的方法。 – BaCaRoZzo

+1

感謝您糾正我的問題,併爲您解答! –

+1

@BaCaRoZzo這通常是一個壞主意。 –

回答

1

鑑於將QML與任何C++類接口有多麼微不足道,解決方案在C++中並不是問題。

QFileInfo(filePath).fileName()這樣做,如果filePath是從文件對話框返回的路徑。你只需將其暴露在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(); 
} 

從QML,簡單地調用appHelper.fileNameFromPath(path)

相關問題