使用 Qt Creator 進行 Shadow Build(建構目錄與原始碼分離)時,常見困惑:可執行檔位於 build-xxx/debug/,但程式內 QDir::currentPath() 回傳的是 build-xxx/(建構根目錄)而非執行檔所在目錄。這是預設行為,而非錯誤。
build-xxx/),方便存取專案相對路徑資源(如測試資料、設定檔)。build-xxx/debug/ 或 build-xxx/release/。QCoreApplication::applicationDirPath() 才會回傳執行檔所在目錄。%(build_dir)/debug(執行檔目錄)或 %{source_dir}(原始碼目錄)。// 取得執行檔所在目錄(推薦用於載入同目錄資源)
QString exeDir = QCoreApplication::applicationDirPath();
// 取得專案原始碼目錄(需透過建構系統傳入,如 DEFINES += SRC_DIR=\"$$PWD/\")
// #include "src_dir.h" → QString srcDir = SRC_DIR;
Qt Centre 討論串:How to set run configuration in Qt Creator