windows windows下的Qt应用程序和窗口图标
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6523039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Qt Application and window Icon under windows
提问by Goz
I have created a simple application icon by embedding a standard windows resource file containing an icon. However I would also like to use this icon on my main application window. Is there an easy way to do this? So far it seems the only way would be to seperately load an icon that contains the window icon rather than reusing the already exisiting icon. This seems like a horrible solution. Amongst other things the actual icon is embedded in my executable I don't want to have to distribute it twice.
我通过嵌入包含图标的标准 Windows 资源文件创建了一个简单的应用程序图标。但是我也想在我的主应用程序窗口中使用这个图标。是否有捷径可寻?到目前为止,似乎唯一的方法是单独加载一个包含窗口图标的图标,而不是重用已经存在的图标。这似乎是一个可怕的解决方案。除其他外,实际图标嵌入在我的可执行文件中,我不想将其分发两次。
Anyone know how to do this?
有人知道怎么做吗?
回答by Goz
Actually ... turns out its very very simple ...
实际上......原来它非常非常简单......
HICON hIcon = (HICON)LoadImage( GetModuleHandle( nullptr ), MAKEINTRESOURCE( IDI_ICON1 ), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE | LR_LOADTRANSPARENT );
setWindowIcon( QIcon( QtWin::fromWinHICON( hIcon ) ) );
::DestroyIcon( hIcon );
回答by pokey909
I think the post from Goz is a good match for your question. But if you want to avoid using the native Windows API (which is actually preferrable since setting the application icon is platform dependent) I would opt for this seemingly less elegant approach:
我认为 Goz 的帖子非常适合您的问题。但是,如果您想避免使用本机 Windows API(这实际上是可取的,因为设置应用程序图标取决于平台),我会选择这种看似不太优雅的方法:
1) in your .pro file:
win32:RC_FILE=your_rcfile_with_icon.rc
RESOURCES += qt_Resource_file.qrc
2) Add the same icon as in your .rc file to the qt .qrc file (i.e. embedd it twice)
3) in your main file:
setWindowIcon(QIcon(":/the_icon.ico"));
This avoids native API calls and your code remains portable. SEttign the application icon is unfortunatly different for every platform. So you should really avoid the native calls if you want portable code.
这避免了原生 API 调用并且您的代码保持可移植性。不幸的是,每个平台的设置应用程序图标都不同。所以如果你想要可移植的代码,你真的应该避免本地调用。