JC2102
JC2102

Reputation: 55

How can I program the function "go back" as a Menu Bar option of a MainWindow in QT?

I am working in a Program in QT where I have a LOGIN Dialog, if the person is logged successfully then the program shows a MainWindow object. There's a Menu Bar in that object. One of the options of the Menu Bar is LOGOUT, then what can I do to make the MainWindow object close or hide and the LOGIN Dialog show again?

Here's what I tried:

In the main.cpp

Dialog login;

if (login.exec() == QDialog::Rejected)
{
    return -1;
}

MainWindow mainWindow;
mainWindow.show();

In the LOGOUT function from the Menu Bar:

void MainWindow::on_actionLogOut_triggered()
{
    close();
    //What else can I do here to make the LOGIN Dialog appear again?
}  

I also tried to create a new LOGIN object in the on_actionLogOut_triggered() method but it goes out of the scope and the new Dialog object disappear immediately.

Upvotes: 3

Views: 205

Answers (1)

Francis Cugler
Francis Cugler

Reputation: 7905

Here you would need a finite state machine...

Depending on which state your application is in and which functions are called will determine the behavior of the overall system. You will want to have your own functions to show a login window, to show the main window, to log in, to log out, etc... then you need to build your structure with the appropriate logic.

Pseudo Example:

enum class AppState {
    LOGGED_IN,
    LOGGED_OUT,
};

class Application  {
   AppState state_;
public:
    Application() : state_{AppState::LOGGED_OUT} {
        run();
    }

    ~Application() {
        exitApp();
    }

    void exitApp() {
        // clean up resources
        closeMainWindow(true);
    }

    void run() {
        do {
            presentLoginScreen();
        } while(state_ != AppState::LOGGED_IN);

        if (state_ == AppState::LOGGED_IN) {
            while (state_ != AppState::LOGGED_OUT)
                // do stuff
        }
    }

    void logIn(/*user input*/) {
        // test input
    }

    void logOut() {
        if(state_ == AppState::LOGGED_IN) {
            closeMainWindow();
            state_ = AppState::LOGGED_OUT;
            presentLogginScreen();
        }
    }

    void presentLogginScreen() {
        // display the login screen 

        // get user input
        logIn(/*user input*/);

        // if user input matches credentials sign them in and show the main window
        if( credentials == valid_credentials ) {
            showMainWindow();
            state_ = AppState::LOGGED_IN;
        } 
    }

    void closeMainWindow(bool exitApp) {
        if(exitApp) // cleanup memory and shutdown
        else // otherwise just close window and present login screen
    }

}; 

Upvotes: 1

Related Questions