简体   繁体   中英

Wrong background color in custom QWidget

In my GUI, I have a scrollable area and a widget to be displayed in it defined like so:

_scoreBoxScroll = new QScrollArea(this);
_scoreBoxScroll->setFrameShape(QFrame::NoFrame);
_scoreBoxWidget = new QWidget(this);
_scoreBoxWidgetLayout = new QHBoxLayout(_scoreBoxWidget);

Some custom widgets are added later in a function:

for (int i = 1; i <= _db->gamesPerRound(); ++i) {
    GameWidget *newGame = new GameWidget(_scoreBoxWidget, i, _db->playersString(MT::singular), _db->boogerScore());
    _scoreBoxWidgetLayout->addWidget(newGame);
}

_scoreBoxScroll->setWidget(_scoreBoxWidget);

This results in a wrong background color for the GameWidgets: 小部件的背景色错误

When I add those widgets in the constructor with the very same code (and the _db calls replaced with static values, as when the constructor is called, there's no _db yet), the widgets are displayed with the correct color: 具有正确背景颜色的小部件

In case this is interesting: the whole code can be found in git://l3u.de/muckturnier.git, the posted code resides in ScorePage/ScorePage.cpp.

Why is a different color displayed here? And how can I fix this? Thanks in advance for all help!

Edit: the code in the constructor used in the second example is (as I don't have _db there):

_scoreBoxWidget = new QWidget(this);
_scoreBoxWidgetLayout = new QHBoxLayout(_scoreBoxWidget);
_scoreBoxLayout->addWidget(_scoreBoxWidget);

for (int i = 1; i <= 2; ++i) {
    GameWidget *newGame = new GameWidget(this, i, QString::fromUtf8("Paar"), 21);
    _scoreBoxWidgetLayout->addWidget(newGame);
}

_scoreBoxScroll->setWidget(_scoreBoxWidget);

Edit: I have created a minimalistic demo in the "demo" branch on git://l3u.de:muckturnier.git – I would be very glad if anyone could explain this behaviour!

Okay, I can answer my question myself now. It's due to the fact that QScrollArea::setWidget() calls setAutoFillBackground(true) on the added widget. When I add a manual

_scoreBoxWidget->setAutoFillBackground(false);

after the

_scoreBoxScroll->setWidget(_scoreBoxWidget);

the background color is as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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