Qt程序开机启动的怪现象————无法正常显示程序皮肤

事情很简单:最近公司项目在做即时通讯软件,类似QQ。该软件应该支持开机启动这样的常用功能。但是实际上开发该功能的时候碰到了个问题:开机启动程序无法正常加载皮肤文件。

这个问题让我头疼了很久啊。最终确定问题出现在程序的打包皮肤文件上。因为界面使用的是qt所以,皮肤等资源文件都是应该放在qrc文件中进行统一管理的。但是实际上该程序的资源文件却都是在外面的。这样的结果就是正常启动程序没有问题,开机启动就会加载不上皮肤文件。

下面就是我想到的解决方法:

方法一:修改qrc文件,将所有的资源文件都添加到qrc文件中进行管理。这样问题就应该能够解决。另外我找到了官方的style的具体使用方法,具体使用方式和我说的基本一致。

方法二(我师父想出来的):修改程序运行时的所在目录。这个不太好理解。大概是windows启动的时候,程序虽然启动了,但是程序所在的文件夹却没有被识别,导致开机启动无法正常加载皮肤资源的等文件。具体解决办法就是在程序的main函数中设置程序所在目录。请看代码选段:

 1 //获取当前exe文件所在路径
 2 std::string get_app_run_path()
 3 {
 4     char szFilePath[MAX_PATH + 1]; 
 5     GetModuleFileNameA(NULL, szFilePath, MAX_PATH); 
 6     (strrchr(szFilePath, ('\')))[1] = 0;//删除文件名,只获得路径
 7     return std::string(szFilePath);
 8 }
 9 bool GetCurrentProcessDirectory(std::wstring &wstrCurrentProcessPath)
10 {
11     bool is_success = false;
12 
13     do 
14     {
15         WCHAR *lpProcessPath = (WCHAR* )malloc(sizeof(WCHAR)*MAX_PATH);
16         if (lpProcessPath)
17         {
18             ZeroMemory(lpProcessPath, MAX_PATH);
19             DWORD nBufferLength = MAX_PATH;
20             is_success = GetCurrentDirectory(nBufferLength, lpProcessPath);
21             wstrCurrentProcessPath = lpProcessPath;
22             free(lpProcessPath);
23             lpProcessPath = NULL;
24         }
25 
26     } while (false);
27 
28     return is_success;
29 }
30 
31 int main(int argc,char**argv)
32 {
33 
34     std::wstring wstrCurrentProcessPath;
35     GetCurrentProcessDirectory(wstrCurrentProcessPath);
36     std::string strCurrentProcessPath = get_app_run_path();
37     SetCurrentDirectoryA(strCurrentProcessPath.c_str()  );
38 。。。
39 
40     QApplication a(argc,argv);
41 
42     QFile file(QString( "../qss/gocomUi.qss") );
43     file.open( QFile::ReadOnly );
44     QString styleSheet = QLatin1String( file.readAll() );
45     file.close();
46 
47     a.setStyleSheet( styleSheet );
48 
49     a.setStyle(new CProxyStyle);//去除焦点虚框
50 
51 
52     mainWindow w;
53     w.show();
54 
55 。。。
56     int rt = a.exec();
57     return rt;
58 }

使用SetCurrentDirectoryA(strCurrentProcessPath.c_str() );就完成了程序所在目录的设置工作。

*注:

SetCurrentDirectory function

Changes the current directory for the current process.

参考:http://msdn.microsoft.com/en-us/library/windows/desktop/aa365530%28v=vs.85%29.aspx

原文地址:https://www.cnblogs.com/superstargg/p/4024607.html