无法在 Qt 样式表中设置背景图像

时间:2023-01-22
本文介绍了无法在 Qt 样式表中设置背景图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过带有参数样式表的命令行运行我的 Qt 应用程序.控件的样式有效,但在我尝试为 MainWindow 加载背景图像时无效.我试过了:

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:

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?

推荐答案

您尝试使用的图像在哪里?

Where is located the image you are trying to use ?

您是否将其作为应用程序的资源?

Did you put it as a resource of your application ?

如果您想使用属于资源一部分的图像,您的项目中应该有一个资源文件 (*.qrc).该文件应包含如下内容:

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 :

<RCC>
   <qresource prefix="/images">
      <file alias="sunset.jpg">sunset.jpg</file>
   </qresource>
</RCC>

然后,您可以在 QMainWindow 的构造函数中编写此代码:

Then, you could write this code in the constructor of your QMainWindow :

setStyleSheet("background-image: url(:/images/sunset.jpg);");

如果您不想使用 Qt 资源系统,您可以将图像的路径放在磁盘上:

If you don't want to use the Qt resource system, you can just put the path to your image on your disk :

setStyleSheet("background-image: url(res/images/sunset.jpg);");

但如果您使用相对路径请小心:Qt 将从当前位置开始,这可能会改变,特别是如果您使用 Qt Creator 进行开发.

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 Creator,当您在调试模式下运行应用程序时,当前路径在 debug/ 中.当您在发布模式下运行您的应用时,当前路径位于 release/(除非您更改了设置).

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 样式表中设置背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:使 QLabel 表现得像一个超链接 下一篇:具有不同文本颜色的 QTextEdit (Qt/C++)

相关文章

最新文章