C++ 无法在 Qt 样式表中设置背景图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4458201/
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
Unable to set the background image in Qt Stylesheet
提问by Owen
I'm running my Qt app through command line with a parameter -stylesheet. The styles for the controls work but not when I'm trying to load a background image for the MainWindow. I tried:
我正在通过带有参数样式表的命令行运行我的 Qt 应用程序。控件的样式有效,但在我尝试为 MainWindow 加载背景图像时无效。我试过:
QMainWindow{
background-image:url(:image_256_8bit_latest_back.png);
}
Also tried removing the ":" in background, but doesn't make a difference. Can somebody tell me what's wrong with this StyleSheet?
还尝试删除背景中的“:”,但没有任何区别。有人能告诉我这个样式表有什么问题吗?
回答by Jér?me
Where is located the image you are trying to use ?
您尝试使用的图像位于何处?
Did you put it as a resourceof your application ?
你把它作为你的应用程序的资源了吗?
If you want to use an image which is part of your resources, you should have a resource file (*.qrc
) in your project. This file should contain something like this :
如果您想使用属于资源一部分的图像,您的项目中应该有一个资源文件 ( *.qrc
)。该文件应包含如下内容:
<RCC>
<qresource prefix="/images">
<file alias="sunset.jpg">sunset.jpg</file>
</qresource>
</RCC>
Then, you could write this code in the constructor of your QMainWindow
:
然后,您可以在您的构造函数中编写此代码QMainWindow
:
setStyleSheet("background-image: url(:/images/sunset.jpg);");
If you don't want to use the Qt resource system, you can just put the path to your image on your disk :
如果您不想使用Qt 资源系统,您可以将图像的路径放在磁盘上:
setStyleSheet("background-image: url(res/images/sunset.jpg);");
Be careful though if you are using a relative path : Qt will start from the current location, which might change, particularly if you are developping with Qt Creator.
但如果您使用的是相对路径,请小心:Qt 将从当前位置开始,这可能会改变,特别是如果您使用Qt Creator进行开发。
With Qt Creator, when you run your app in debug mode, the current path is in debug/
. When you run your app in release mode, the current path is in release/
(unless you changed the settings).
使用Qt Creator,当您在调试模式下运行您的应用程序时,当前路径在debug/
. 当您在发布模式下运行您的应用程序时,当前路径在release/
(除非您更改了设置)。
回答by koan
Clearly there is a problem with the path to your image. Try using an absolute path to verify the image is loaded by QT and working.
显然,您的图像路径存在问题。尝试使用绝对路径来验证图像是否由 QT 加载并正常工作。