C++ and Qt, how do I run either the constructor function or a different function on object creation to setup a Ui?

StackOverflow https://stackoverflow.com/questions/22506727

  •  17-06-2023
  •  | 
  •  

Question

In Qt, I have a class with a slot, called on_pushButton_2_clicked(), in this function, I would like to instantiate another class, Login, and run setupUi on its ui element.

Currently, this is what I have:

in WelcomeScreen.cpp

void WelcomeScreen::on_pushButton_2_clicked()
{
    Login login(this);
    login.init();
}

and in Login.cpp

void Login::init(){
    ui->setupUi(this);

    QPalette wPal(palette());
    wPal.setColor(QPalette::Background,Qt::white);
    ui->success->setAutoFillBackground(true);
    ui->success->setPalette(wPal);
    ui->success->hide();
    ui->failure->setAutoFillBackground(true);
    ui->failure->setPalette(wPal);
    ui->failure->hide();
}

This compiles and runs fine, but it doesn't load the login ui upon the button press. This, does load the UI:

In WelcomeScreen.cpp

void WelcomeScreen::on_pushButton_2_clicked()
{
    Ui::Login login_ui;
    login_ui.setupUi(this);
}

However, it doesn't run the Login constructor or any of its functions so I can't initialize it like I'd like to.

Ideally, I'd like to simply instantiate the Login object and have it run the constructor, thus setting up the Ui and running all of the initialization.

Also, here's the Login constructor (it's basically the default constructor)

Login::Login(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Login)
{
init();

}
Was it helpful?

Solution

In your WelcomeScreen::on_pushButton_2_clicked() function, your Login object will be destroyed once the function finishes. This is because it goes out of scope. You can solve this by either initializing it with new, or making it a member variable. You can also use QSharedPointer or a similar class.

I don't know how your Login class is supposed to work, so in my example I will delete it when it is closed.

void WelcomeScreen::on_pushButton_2_clicked()
{
    Login *login = new Login(this);
    login->setAttribute(Qt::WA_DeleteOnClose);
    login->init();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top