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

Unable to set the background image in Qt Stylesheet(无法在 Qt 样式表中设置背景图像)
本文介绍了无法在 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 样式表中设置背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Bring window to front -gt; raise(),show(),activateWindow() don’t work(把窗户放在前面 -raise(),show(),activateWindow() 不起作用)
How to get a list video capture devices NAMES (web cameras) using Qt (crossplatform)? (C++)(如何使用 Qt(跨平台)获取列表视频捕获设备名称(网络摄像机)?(C++))
How to compile Qt as static(如何将 Qt 编译为静态)
C++ over Qt : Controlling transparency of Labels and Buttons(C++ over Qt:控制标签和按钮的透明度)
How to know when a new USB storage device is connected in Qt?(Qt如何知道新的USB存储设备何时连接?)
What is an event loop in Qt?(Qt 中的事件循环是什么?)