Question

I'm starting with Qt. Previously I did with Java Swing, where I accomplished this by Card Layout. I have MainWindow, Login Widget and Dashboard Widget.

MainWindow.cpp

MainWindow::MainWindow(QWidget *parent) : 
    QMainWindow(parent), 
    ui(new Ui::MainWindow) 
{
    ui->setupUi(this);

    // set login screen on startup
    QWidget *login = new Login(this);
    setCentralWidget(login);
}

Login.cpp

#include "login.h"
#include "ui_login.h"

Login::Login(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Login)
{
    ui->setupUi(this);
}

Login::~Login()
{
    delete ui;
}

void Login::on_loginButton_clicked()
{
    // some logic
    // here I want to create Dashboard widget in central widget
    // but method setCentralWidget() can't be called from here
}
Was it helpful?

Solution

You want to use signals and slots to communicate between the windows. QDialog provides three important signals in particular: accepted(), rejected(), finished(int). So you'll want to do something like this:

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), 
      ui(new Ui::MainWindow) 
{
    ui->setupUi(this);

    // set login screen on startup
    QWidget *login = new Login(this);
    connect(login, SIGNAL(finished(int)), this, SLOT(loginFinished(int)));

    setCentralWidget(login);
}

MainWindow::loginFinished(int reason)
{
    Login *login = qobject_cast<Login*>(sender());
    if (!login) {
        qDebug() << "something bad happened!";
        return;
    }

    login->deleteLater();
    setCentralWidget(someOtherWidget);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top