简体   繁体   English

Qt 使用调色板更改 QWidget 的背景颜色不起作用

[英]Qt changing the background color of QWidget using palette doesn't work

I want to change the background color in a custom subclass of QWidget.我想在 QWidget 的自定义子类中更改背景颜色。 Here is the code:这是代码:

WorldView::WorldView(QWidget *parent) : QWidget(parent)
{
    QPalette p(palette());
    p.setColor(QPalette::Background, Qt::black);
    setAutoFillBackground(true);
    setPalette(p);
}

But it doesn't work as expected.但它没有按预期工作。 The background color remains unchanged.背景颜色保持不变。

I don't know why.我不知道为什么。

As you can read in the documentation , QPalette::Background is obsolete.正如您在文档中所读到的, QPalette::Background已过时。 Use QPalette::Window instead.请改用QPalette::Window Note that some widgets use some other role for the background.请注意,某些小部件使用其他角色作为背景。 See the QPalette::ColorRole documentation请参阅QPalette::ColorRole 文档

Also:还有:

Warning: Some styles do not use the palette for all drawing, for instance, if they make use of native theme engines.警告:某些样式不会将调色板用于所有绘图,例如,如果它们使用本机主题引擎。 This is the case for both the Windows XP, Windows Vista, and the OS X styles. Windows XP、Windows Vista 和 OS X 样式都是这种情况。

In this case I suggest to use style sheets.在这种情况下,我建议使用样式表。 See Qt Style Sheets Reference参见Qt 样式表参考

However, if WorldView is a custom widget, with your custom paintEvent , it's up to you to draw the background但是,如果 WorldView 是一个自定义小部件,使用您的自定义paintEventpaintEvent您来绘制背景

Use QPalette::Base instead of QPalette::Background使用QPalette::Base而不是QPalette::Background

 QPalette p(palette());
 p.setColor(QPalette::Base, Qt::lightGray);
 setPalette(p);

For some reason custom widget uses QPalette::Base for filling backgound出于某种原因,自定义小部件使用QPalette::Base来填充背景

setStyleSheet('background-color:black;')

If the palette color doesnt work then it can have four reasons you should check如果调色板颜色不起作用,则可能有四个原因您应该检查

  • you have set the colors from style sheets which i don't recommend at all or maybe you have set the parents stylesheet您已经设置了我根本不推荐的样式表的颜色,或者您已经设置了父样式表

  • your color role in the palette doesnt match您在调色板中的颜色角色不匹配

  • make sure the palette is set for widget and i dont recommend to set palette for every widget unless you really wanted to, you should set the palette for your application确保为小部件设置了调色板,我不建议为每个小部件设置调色板,除非您真的想要,您应该为您的应用程序设置调色板

  • or maybe your window manager is forcing colors and palettes dont work at all或者也许您的窗口管理器正在强制颜色和调色板根本不起作用

Thats all i got in my mind, if you know more, please edit this answere and add it to items这就是我的全部想法,如果您知道更多,请编辑此答案并将其添加到项目中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM