CDT
CDT

Reputation: 10621

Switch between QMainWindows

I have three QMainWindows, EntryWindow, WindowA, WindowB. There are 2 buttons in EntryWindow, clicking buttonA displays WindowA and exits EntryWindow, clicking buttonB displays WindowB and exits EntryWindow.

In main.cpp:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QTextCodec::setCodecForCStrings(QTextCodec::codecForLocale());
    Entry w;
    w.show();
    return a.exec();
}

In entryWindow.cpp:

void Entry::on_chooseABtn_clicked()
{
    this->hide();
    WindowA w;
    w.show();
}

void Entry::on_chooseBBtn_clicked()
{
    this->hide();
    QTextCodec::setCodecForCStrings(QTextCodec::codecForLocale());
    WindowB w;
    w.show();
}

But this doesn't seem to work. After clicking the button, WindowA or WindowB just flashed off. How should I modify the code ?

Upvotes: 0

Views: 130

Answers (2)

laurent
laurent

Reputation: 90736

Create the windows as pointers, otherwise they get deleted automatically when they fall out of scope:

this->hide();
WindowA* w = new WindowsA(this);
w->show();

Upvotes: 3

Michał Ciuba
Michał Ciuba

Reputation: 7944

You create instances of WindowA and WindowB classes on stack:

WindowA w;

so they are deleted when method returns, just after

w.show();

Maybe add these windows as instance variables to Entry class.

EDIT: some code sample. In .h file:

class Entry : public QMainWindow {

//your stuff

private:

WindowA windowA;
WindowB windowB;

} 

and you can change your button click handlers like that:

void Entry::on_chooseABtn_clicked()
{
    this->hide();
    windowA.show();
}

Upvotes: 5

Related Questions