Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to create a childwidget with other color as parent



  • I want to make a black mainwindow with a yello label in the window, (not in designer-mode).
    I tried this:

        mainWindow.setFixedSize(1100, 900);
        mainWindow.setPalette(QPalette(Qt::black));
    
        QLabel* brett = new QLabel(&mainWindow);
        brett->setFixedSize(800, 800);
        brett->move(10, 10);
    
        brett->setPalette(QPalette(QPalette::Base, Qt::yellow));
    
        brett->show();
        mainWindow.show();
    

    the mainwindow gets black, correctly, but the label is also black. (because its a child of the mainwindow

    I tried this:

    mainWindow.setFixedSize(1100, 900);
        mainWindow.setPalette(QPalette(Qt::black));
    
        QLabel* brett = new QLabel();
        brett->setFixedSize(800, 800);
        brett->move(10, 10);
    
        brett->setPalette(QPalette(QPalette::Base, Qt::yellow));
    
        brett->show();
        mainWindow.show();
    

    now the label is yello, but its not a child of the mainwindow more, and so its showed in a new window.

    How to change the Color of one Label, without changing the color of the parent?


  • Moderators

    @Lukas02
    use "QPalette::Background" for the child widget



  • @Lukas02

    You can use a stylesheet for your mainWindow to make the background black and another stylesheet to make your label yellow.

    setStylesheet("QMainWindow#myWindow { background: black; }");
    brett->setStylesheet("QLabel#brett { color: yellow; }");
    

    brett->move(10, 10);

    You usually want to put your label in a layout.



  • @raven-worx
    i already tried this. But thx

    QLabel* brett = new QLabel(&mainWindow);
        brett->setFixedSize(800, 800);
        brett->move(10, 10);
    
        brett->setPalette(QPalette(QPalette::Background, Qt::yellow));
    

    the same problem



  • @Pl45m4
    The StyleShet - version fixed the problem. Thak you.
    But I dont understand my mistake in my first version.



  • @Lukas02 said in How to create a childwidget with other color as parent:

    But I dont understand my mistake in my first version.

    QWidget propagates explicit palette roles from parent to child. If you assign a brush or color to a specific role on a palette and assign that palette to a widget, that role will propagate to all the widget's children, overriding any system defaults for that role. Note that palettes by default don't propagate to windows (see isWindow()) unless the Qt::WA_WindowPropagation attribute is enabled.

    (from: https://doc.qt.io/qt-5/qwidget.html#palette-prop)


Log in to reply