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

How do I change the background color of my QWidget?



  • Hi, I'm new to this. And I started learning C++ 2 weeks ago, and I'm finding qt overwhelming on the programming part. But anyway, if you created a new project, how do you change the background color of QWidget? I mean I looked at the qt documentation but I can't understand anything. They say I can use QPalette but where do I write the code? I really don't understand it. Please help.


  • Lifetime Qt Champion

    Hi and welcome to the forums.
    You can write the code in MainWindow after the setupUI function.

    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
    
        QPalette pal = ui->widget->palette();
    
        // set black background
        pal.setColor(QPalette::Background, Qt::black);
        ui->widget->setAutoFillBackground(true);
        ui->widget->setPalette(pal);
        ui->widget->show();
    
    

    if you used UI files to make the app.
    You can also do it in your widgets constructor if you made a subclass.

    You can also use stylesheets to change color if you wish.

    https://wiki.qt.io/How_to_Change_the_Background_Color_of_QWidget


Log in to reply