Search code examples
c++qtqcoreapplication

When is QCoreApplication valid?


I want to get the application path however when I run the application in Qt Creator, the applicationPath() method returns an empty string:

    int main(int argc, char *argv[]) {   
        QLoggingCategory::setFilterRules("*.info=false\n");
        QCoreApplication::setOrganizationName("company name");
        QCoreApplication::setOrganizationDomain("companydomain.com");
        QCoreApplication::setApplicationName("AppName");

    #ifdef QT_DEBUG
        //Install logging message handler
        Logger::LogManager::setApplicationPath(QCoreApplication::applicationFilePath());
        qInstallMessageHandler(Logger::LogManager::logMsg);
        qDebug() << "built with debug";
    #else
        qDebug() << "built for release";
    #endif
    ...

Solution

  • I'll explain the issue even when your actual problem was different.

    QCoreApplication computes the file path and the default application name based on the executable. The executable is taken from the first command-line argument, argv[0].

    You must first instantiate the QCoreApplication with those arguments (even when they are static, they access an internal singleton which must be initialized).

    Actually, Qt gives you a console warning when accessing such methods without any previous instance:

    QCoreApplication::applicationFilePath: Please instantiate the QApplication object first

    #include <QCoreApplication>
    #include <QDebug>
    
    int main(int argc, char *argv[])
    {
      qDebug() << "applicationFilePath" << QCoreApplication::applicationFilePath();
      qDebug() << "applicationName" << QCoreApplication::applicationName();
      QCoreApplication a(argc, argv);
      qDebug() << "applicationFilePath" << QCoreApplication::applicationFilePath();
      qDebug() << "applicationName" << QCoreApplication::applicationName();
    
      return a.exec();
    }
    

    Output

    CoreApplication::applicationFilePath: Please instantiate the QApplication object first
    applicationFilePath ""
    applicationName ""
    applicationFilePath "D:/src/stackoverflow/59355035/debug/59355035.exe"
    applicationName "59355035"