QT相对路径显示图片(附获多平台取可执行程序路径方法)

1. 图片不能正常显示

QT在用相对路径显示图片的时,可能会遇到不能正常显示,原因在于图片的相对路径相对于QT程序工作目录而言。

2. QT程序的工作目录

例如在Mac下编译的app程序,使用”open *.app”启动程序的时候,工作目录为系统的根目录“/”。可以使用以下代码在程序中输出调试:

[source lang=”cpp”]
// ….
#include <QDir>
#include <QMessageBox>;

int main(int argc, char *argv[])
{
// ….

QDir dir;
QString pathname;
QMessageBox box;

pathname = dir.currentPath();
box.setText(pathname);
box.exec();

// ……
}

[/source]

2. 设置QT程序工作目录

我们可以通过QDir的静态函数setCurrent() 来设置我们QT App工作的目录,例如APP所在目录,避免相对路径所带来的问题。

[source lang=”cpp”]

int main(int argc, char *argv[])
{
// ….

QDir dir;
dir.setCurrent("dir_name");

// ….
}
[/source]

4. 获取程序运行的当前目录

4.1 Windows平台

[source lang=”cpp”]
#include <Windows.h>
#include <shlwapi.h>

std::string GetExeDir()
{
static wchar_t szbuf[MAX_PATH];
::GetModuleFileNameW(NULL,szbuf,MAX_PATH);
::PathRemoveFileSpecW(szbuf);
char* utf8 = Unicode2Utf8(szbuf);

std::string path;
path.append(utf8);
free(utf8);
return path;
}

[/source]

4.2 MAC OSX平台

[source lang=”cpp”]
#import <Foundation/Foundation.h>
#include <mach-o/dyld.h>
#include <string.h>

std::string GetExeDir()
{
char buf[0];
uint32_t size = 0;
int res = _NSGetExecutablePath(buf,&size);

char* path = (char*)malloc(size+1);
path[size] = 0;
res = _NSGetExecutablePath(path,&size);

char* p = strrchr(path, ‘/’);
*p = 0;
std::string pathTemp;
pathTemp.append(path);
free(path);
return pathTemp;
}
[/source]

4.3 Unix平台

[source lang=”cpp”]

#include <stdio.h>
#include <unistd.h>

char * get_exe_path(char * buf, int count)
{
int i;
int rslt = readlink("/proc/self/exe", buf, count – 1);
if (rslt < 0 || (rslt >= count – 1))
{
return NULL;
}
buf[rslt] = ‘\0’;

// 删除最后的程序名
for (i = rslt; i >= 0; i–)
{
// printf("buf[%d] %c\n", i, buf[i]);
if (buf[i] == ‘/’)
{
buf[i + 1] = ‘\0’;
break;
}
}

return buf;
}

// C++ 版本
#include <limits.h>
std::string get_exe_path()
{
int i;
char buf[PATH_MAX];
int rslt = readlink("/proc/self/exe", buf, PATH_MAX – 1);
if (rslt < 0 || (rslt >= count – 1))
{
return "";
}

buf[rslt] = ‘\0’;

// 删除最后的程序名
for (i = rslt; i >= 0; i–)
{
// printf("buf[%d] %c\n", i, buf[i]);
if (buf[i] == ‘/’)
{
buf[i + 1] = ‘\0’;
break;
}
}

return buf;
}
[/source]

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注