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

I'm trying to change the background color of my QWidget but it's not working.



  • #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QWidget>
    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();
    
    
    }
    
    MainWindow::~MainWindow()
    {
        delete ui;
    }
    

    I'm getting an error : no member named 'widget' in 'Ui::MainWindow'
    I'm still new to this so I don't really know the syntax much. But what does that mean? I'm assuming there's a class called Ui and MainWindow is a function in that class, and there's no 'widget' in the function MainWindow?


  • Lifetime Qt Champion

    @mghalayini So, you're using QtDesigner to design UI, right? Did you add a widget and named it "widget"?
    MainWindow is not a function it is a class. It has a member variable ui which is of type Ui::MainWindow*. If you add a widget to your UI in designer and name it "widget" then your code will work.

    This shouldn't be needed when using designer:

    ui->widget->show();
    

    Also, you can change palette directly in the designer.


  • Lifetime Qt Champion

    @mghalayini Why did you create a second thread about exact same question? The code you posted is from here: https://forum.qt.io/topic/105515/how-do-i-change-the-background-color-of-my-qwidget
    Why don't you ask there why the code is not working?



  • @jsulm The first time I asked I didn't even know what to write. After I got a reply from @mrjj on the other question, I still got it wrong. Looks like I should just add a widget and name it "widget". Thank you!



  • @mghalayini said in I'm trying to change the background color of my QWidget but it's not working.:

    Looks like I should just add a widget and name it "widget".

    Better build your GUI first and then write code that fit to your GUI, instead of coding some random things and facing name issues later. So adapt your code to your UI, not the other way around :)

    The code given by @mrjj on the other thread was just an example. widget is a placeholder for the widget, whose background color you want to change.


Log in to reply