SPlatten
SPlatten

Reputation: 5760

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

Upvotes: 2

Views: 2609

Answers (2)

cbuchart
cbuchart

Reputation: 11555

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"

Upvotes: 1

SPlatten
SPlatten

Reputation: 5760

I've resolved this issue name by changing my routine to get the application name as that's really what I needed:

    Logger::LogManager::setApplicationName(QCoreApplication::applicationName());

Anyway, QCoreApplication::applicationFilePath() and QCoreApplication::applicationDirPath() are available after creation of a QCoreApplication instance. If you need to get the application path before creation of a QCoreApplication instance, you will need to refer to argv[0] and parse it for your use-case.

Upvotes: 2

Related Questions