[英]How to change backgroundcolor of QLineEdit in a QGraphicsScene
I have a QGraphicsScene
and add a QlineEdit
but changing color just doesn't work. 我有一个
QGraphicsScene
并添加了QlineEdit
但是更改颜色是行不通的。
QGridLayout *layout = new QGridLayout(this);
QGraphicsView *view = new QGraphicsView(this);
QGraphicsScene *scene = new QGraphicsScene(this);
QWidget *widget = new QWidget();
QGridLayout *widgetLayout = new QGridLayout(this);
QLineEdit *le1 = new QLineEdit(widget);
QLineEdit *le2 = new QLineEdit(widget);
widgetLayout->addWidget(le1,1,0);
widgetLayout->addWidget(le2,2,0);
widget->setLayout(widgetLayout);
QPalette paletteRed = le1->palette();
paletteRed.setColor(QPalette::Background,Qt::red);
QPalette paletteGreen = le1->palette();
paletteGreen.setColor(QPalette::Background,Qt::green);
le1->setAutoFillBackground(true);
le1->setPalette(paletteRed); // not working
widget->setPalette(paletteGreen); // working
view->setScene(scene);
scene->addWidget(widget);
ui->centralWidget->setLayout(layout);
layout->addWidget(view);
Do I have to trigger something like update()
( which is not working either to get another color ) if the widget is in a scene? 如果窗口小部件在场景中,我是否必须触发类似
update()
(该操作也无法获得另一种颜色)?
EDIT: 编辑:
created new example Code. 创建了新的示例代码。
I know this works in a normal QWidget
. 我知道这可以在普通的
QWidget
。 Actually the code works fine if i place the QLineEdit
in a normal QFrame
etc but its in a QGraphicsScene
. 实际上,如果我将
QLineEdit
放置在常规QFrame
等中, 但将其放置在QGraphicsScene
则代码可以正常工作。 And in this special case its not working. 在这种特殊情况下,它不起作用。 Text and highlight color etc is also working fine.
文字和突出显示颜色等也可以正常工作。 But backgroud/base/etc ist not.
但是backgroud / base / etc不会。
Setting background color via QPalette does not for my widget, why?
通过QPalette设置背景颜色不适合我的窗口小部件,为什么?
Usually it is autoFillBackground
property not set to true to allow setting background on its own. 通常,
autoFillBackground
属性未设置为true允许autoFillBackground
设置背景。
QPalette palette = pWidget->palette(); // fixed it (need to initialize)
palette.setColor(pWidget->backgroundRole(), bkgndColor); // for background (fixed)
palette.setColor(pWidget->foregroundRole(), fgrndColor); // for foreground
pWidget->setAutoFillBackground(true); // to allow to fill the background
pWidget->setPalette(palette);
Setting the background via stylesheet may also work because it forces autoFillBackground == true
mode. 通过样式表设置背景也可能有效,因为它会强制使用
autoFillBackground == true
模式。
I would like to suggest a slight modification on AlexanderVX's answer. 我想对AlexanderVX的答案进行一些修改。 In the first line I would write:
在第一行中,我将编写:
QPalette palette = pWidget->palette();
Just to make sure you tune just what you need of the base object palette. 只是要确保您调整的是基础对象调色板的所需内容。
Regards. 问候。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.