【问题标题】:How to change backgroundcolor of QLineEdit in a QGraphicsScene如何在 QGraphicsScene 中更改 QLineEdit 的背景颜色
【发布时间】:2016-05-26 13:48:25
【问题描述】:

我有一个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);

如果小部件在场景中,我是否必须触发 update() 之类的东西(也无法获得另一种颜色)?

编辑:

创建了新的示例代码。

我知道这适用于普通的QWidget。实际上,如果我将QLineEdit 放在普通的QFrameetc 它在QGraphicsScene 中,则代码可以正常工作。在这种特殊情况下,它不起作用。文本和突出显示颜色等也可以正常工作。但背景/基础/等不是。

【问题讨论】:

  • 变色码在哪里?
  • 改变QPallette ?
  • 尝试使用qt样式表
  • 它不像我不能改变任何东西,我可以改变Text颜色但我不能改变`background'或'base'
  • 问题解决了吗?在 textedit 中放置 lineedit 时我遇到了同样的问题

标签: c++ qt qgraphicsscene qlineedit


【解决方案1】:

我想建议对 AlexanderVX 的回答稍作修改。在第一行我会写:

QPalette palette = pWidget->palette();

只是为了确保您调整基本对象调色板所需的内容。

问候。

【讨论】:

    【解决方案2】:

    通过 QPalette 设置背景颜色不适用于我的小部件,为什么?

    通常是 autoFillBackground 属性未设置为 true 以允许自行设置背景。

    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);
    

    通过样式表设置背景也可能有效,因为它强制使用autoFillBackground == true 模式。

    【讨论】:

    • QPalette::Background 应替换为 pWidget->backgroundRole()。此处信息:doc.qt.io/qt-5/qwidget.html#backgroundRole
    • @JonHarper 是的,最好获得实际的背景角色。然后在我自己的代码中进行修复。所以规则!
    • @AlexanderVX 这正在工作。它在正常情况下工作,如QFrameQLineInput(如果用于普通小部件)。但是如果我输入 QGraphicsScene 它就不起作用
    • @J.W.但是,您的代码中有一件可疑的事情: QPalette pal(QApplication::palette());你可以试试 QLineEdit 自己的调色板吗?
    • @J.W.尝试捕获从addWidget 返回的指向QGraphicsProxyWidget 的指针并在其上设置调色板。
    【解决方案3】:

    我有一个类似的问题,背景颜色只是为轮廓着色:

    问题是有一个边框图像集。设置border-image: none;后背景色出现

    【讨论】:

      猜你喜欢
      • 2015-02-01
      • 2011-11-11
      • 1970-01-01
      • 2011-07-01
      • 2018-12-31
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多