E.F
E.F

Reputation: 199

Change background color of a Qlayout containing QButtons

I have this Qt code:

QHBoxLayout *taggerBox = new QHBoxLayout;
falseBtn = new QToolButton;
falseBtn->setText(tr("False"));
voidBtn = new QToolButton;
voidBtn->setText(tr("Void"));
taggerBox->addWidget(falseBtn);
taggerBox->addWidget(voidBtn);

I would like to change the background of the QHBoxLayout (NOT the background of each button). I didn't find any way to change the background color of a QLayout.

How can I do this ?

Thanks!

Upvotes: 3

Views: 17057

Answers (3)

You'll have to add an intervening widget that you set the layout on, and change that widget's background. E.g.

auto *taggerBox = new QWidget;
auto *layout = new QHBoxLayout(taggerbox);
falseBtn = new QToolButton(tr("False"));
voidBtn = new QToolButton(tr("Void"));
layout->addWidget(falseBtn);
layout->addWidget(voidBtn);
auto palette = taggerBox->palette();
palette.setColor(QPalette::Window, Qt::blue);
taggerBox->setPalette(palette);

If you're doing this in the constructor of some class, then likely the objects have the same lifetime as the class as there's no point to dynamically allocate them. In such circumstances, the widgets and layouts should be class members instead:

class MyClass : ... {
  QWidget taggerBox;
  QHBoxLayout taggerLayout{&taggerBox};
  QToolButton falseBtn{tr("False")};
  QToolButton voidBtn{tr("Void")};
public:
  MyClass(...);
};

MyClass::MyClass(...) : ... {
    taggerLayout.addWidget(&falseBtn);
    taggerLayout.addWidget(&voidBtn);
    auto palette = taggerBox.palette();
    palette.setColor(QPalette::Window, Qt::blue);
    taggerBox.setPalette(palette);
    ...
}

Upvotes: 3

Konstantin T.
Konstantin T.

Reputation: 1013

Since QHBoxLayout is not a QWidget it hasn't its own appearance. So you can't change its color.

Upvotes: 3

Swift - Friday Pie
Swift - Friday Pie

Reputation: 14589

QLayout is not a visual element, it's a container that adjust location of contained widgets. You can change background of QFrame or other widgets you included QLayout into.

Upvotes: 4

Related Questions