2011-09-13 13 views
55

Estoy escribiendo un programa en C++ utilizando la biblioteca Qt. Hay un enlace simbólico en el directorio bin de mi casa al ejecutable. Me gustaría que el directorio de trabajo actual de mi programa sea el directorio en el que estoy con mi terminal (es decir, el resultado del comando pwd). Vi la función QDir::currentPath(), pero devuelve el directorio donde está el binario.Obtener el directorio de trabajo actual en una aplicación Qt

¿Cómo puedo encontrar mi directorio de trabajo actual?

+1

¿El constructor por defecto QDir dan el mismo resultado? – cmannett85

+2

Sí: 'QDir dir; Cout << dir.absolutePath() << flush; 'me da el directorio donde vive el ejecutable. – Geoffroy

+1

Tanto QDir :: currentPath() como dir.absolutePath() devuelven el directorio actual de la línea de comando. – Flint

Respuesta

2

Gracias RedX y Kaz por sus respuestas. No entiendo por qué me da el camino del exe. Encontré otra manera de hacerlo:

QString pwd(""); 
char * PWD; 
PWD = getenv ("PWD"); 
pwd.append(PWD); 
cout << "Working directory : " << pwd << flush; 

Es menos elegante que una sola línea ... pero funciona para mí.

+0

Lo obtuve también con QFileInfo ("."). AbsolutePath() – crgarridos

71

Just tested y QDir::currentPath() devuelve la ruta desde la que llamé a mi ejecutable.

Y un enlace simbólico no "existe". Si está ejecutando un archivo ejecutable de esa ruta, lo está ejecutando efectivamente desde la ruta a la que apunta el enlace simbólico.

+0

http://doc-snapshot.qt-project.org/4.8/qdir.html#currentPath –

39

Ha intentado QCoreApplication::applicationDirPath()

qDebug() << "App path : " << qApp->applicationDirPath(); 
+6

Si leo la documentación, esto proporciona el directorio donde está el ejecutable. Pero quería el directorio desde el que se llama el ejecutable. – Geoffroy

+0

Esto generalmente funcionará, pero no todos usarán una aplicación QCore. Por ejemplo, mi QTest no me deja usar eso. –

7

Para añadir a la respuesta Kaz, Siempre que estoy haciendo una aplicación QML tiendo a añadir esto a la principal C++

#include <QGuiApplication> 
#include <QQmlApplicationEngine> 
#include <QStandardPaths> 

int main(int argc, char *argv[]) 
{ 
QGuiApplication app(argc, argv); 
QQmlApplicationEngine engine; 

// get the applications dir path and expose it to QML 

QUrl appPath(QString("%1").arg(app.applicationDirPath())); 
engine.rootContext()->setContextProperty("appPath", appPath); 


// Get the QStandardPaths home location and expose it to QML 
QUrl userPath; 
    const QStringList usersLocation = QStandardPaths::standardLocations(QStandardPaths::HomeLocation); 
    if (usersLocation.isEmpty()) 
     userPath = appPath.resolved(QUrl("/home/")); 
    else 
     userPath = QString("%1").arg(usersLocation.first()); 
    engine.rootContext()->setContextProperty("userPath", userPath); 

    QUrl imagePath; 
     const QStringList picturesLocation = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation); 
     if (picturesLocation.isEmpty()) 
      imagePath = appPath.resolved(QUrl("images")); 
     else 
      imagePath = QString("%1").arg(picturesLocation.first()); 
     engine.rootContext()->setContextProperty("imagePath", imagePath); 

     QUrl videoPath; 
     const QStringList moviesLocation = QStandardPaths::standardLocations(QStandardPaths::MoviesLocation); 
     if (moviesLocation.isEmpty()) 
      videoPath = appPath.resolved(QUrl("./")); 
     else 
      videoPath = QString("%1").arg(moviesLocation.first()); 
     engine.rootContext()->setContextProperty("videoPath", videoPath); 

     QUrl homePath; 
     const QStringList homesLocation = QStandardPaths::standardLocations(QStandardPaths::HomeLocation); 
     if (homesLocation.isEmpty()) 
      homePath = appPath.resolved(QUrl("/")); 
     else 
      homePath = QString("%1").arg(homesLocation.first()); 
     engine.rootContext()->setContextProperty("homePath", homePath); 

     QUrl desktopPath; 
     const QStringList desktopsLocation = QStandardPaths::standardLocations(QStandardPaths::DesktopLocation); 
     if (desktopsLocation.isEmpty()) 
      desktopPath = appPath.resolved(QUrl("/")); 
     else 
      desktopPath = QString("%1").arg(desktopsLocation.first()); 
     engine.rootContext()->setContextProperty("desktopPath", desktopPath); 

     QUrl docPath; 
     const QStringList docsLocation = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation); 
     if (docsLocation.isEmpty()) 
      docPath = appPath.resolved(QUrl("/")); 
     else 
      docPath = QString("%1").arg(docsLocation.first()); 
     engine.rootContext()->setContextProperty("docPath", docPath); 


     QUrl tempPath; 
     const QStringList tempsLocation = QStandardPaths::standardLocations(QStandardPaths::TempLocation); 
     if (tempsLocation.isEmpty()) 
      tempPath = appPath.resolved(QUrl("/")); 
     else 
      tempPath = QString("%1").arg(tempsLocation.first()); 
     engine.rootContext()->setContextProperty("tempPath", tempPath); 
engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); 
return app.exec(); 
} 

Su uso en QML

.... 
........ 
............ 
Text{ 
text:"This is the applications path: " + appPath 
+ "\nThis is the users home directory: " + homePath 
+ "\nThis is the Desktop path: " desktopPath; 
} 
+0

Ahora hay un módulo QML de StandardPaths: https://doc.qt.io/qt-5/qml-qt-labs-platform-standardpaths.html –

2

estoy corriendo Qt 5.5 en Windows y el constructor predeterminado de QDir parece recoger el directorio de trabajo actual, no el directorio de la aplicación.

No estoy seguro si el getenv PWD funcionará multiplataforma y creo que está configurado en el directorio de trabajo actual cuando el shell lanzó la aplicación y no incluye ningún cambio de directorio de trabajo realizado por la aplicación misma (que podría ser la razón por la cual el OP está viendo este comportamiento).

Así que pensé que me gustaría añadir algunas otras maneras que debe darle el directorio de trabajo actual (no la ubicación binaria de la aplicación):

// using where a relative filename will end up 
QFileInfo fi("temp"); 
cout << fi.absolutePath() << endl; 

// explicitly using the relative name of the current working directory 
QDir dir("."); 
cout << dir.absolutePath() << endl; 
+0

Gracias Mark, pero he probado sus soluciones con Qt5.3.2 en Linux, y ambas dan la ubicación binaria ... – Geoffroy

Cuestiones relacionadas