PDA

View Full Version : Switching between two windows



Prasad_
15th May 2013, 05:40
I am very much new to Qt and I have a simple doubt on switching between the windows.

I have a main window and I am creating a secondary window using a different class. I am hiding the primary window using hide( ) function and only the second window belonging to different class is visible. When the user presses the close button I have to show back the first window. My code looks something like this.

main.cpp


#include "FirstWindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
FirstWindow w;

w.setAttribute( Qt :: WA_QuitOnClose );
w.show();
return a.exec();
}


Important lines belonging to FirstWindow.h.



#include "SecondWindow.h"
class FirstWindow : public QDialog
{
Q_OBJECT

private:

SecondWindow * window2;

public:
void some_function( ){

this -> hide( );
window2 = new SecondWindow( );
window2 -> displayTheWindow( );
}
}


Important lines belonging to SecondWindow.h




class SecondWindow : public QDialog
{
Q_OBJECT

private:

QDialog * dialog;

public slot:

void startFirstWindow( );

public:
SecondWindow( ){
dialog = new QDialog( );
connect( this, SIGNAL( rejected( ) ), this, SLOT( startFirstWindow( ) ) );
}
}



Can anybody please help me how should I write the slot of startFirstWindow( ). I just want to make the first window visible again. Or is there another approach to this without much changes.

Thanks in advance for the help.

Santosh Reddy
15th May 2013, 08:29
For socond widget to show the fisrt window it should have the firstwindow's handle (pointer), only then it can connect to firtwindow's slot or call hide directly.

Here is an small example to show and hide two widget from one another. Note this just an example how to do it.


#include <QtGui>
#include <QApplication>

class Widget : public QWidget
{
public:
explicit Widget(QWidget * parent = 0)
: QWidget(parent)
, mPushButton(new QPushButton("Hide self and show Partner", this))
, mPartner(0)
{ }

void setPartner(QWidget * partner)
{
if(partner == 0)
return;

if(mPartner != partner)
{
if(mPartner != 0)
{
disconnect(mPushButton, SIGNAL(clicked()), this, SLOT(hide()));
disconnect(mPushButton, SIGNAL(clicked()), mPartner, SLOT(showMaximized()));
}

mPartner = partner;

connect(mPushButton, SIGNAL(clicked()), this, SLOT(hide()));
connect(mPushButton, SIGNAL(clicked()), mPartner, SLOT(showMaximized()));
}
}
private:
QPushButton * mPushButton;
QWidget * mPartner;
};

int main(int argc, char *argv[])
{
QApplication app(argc, argv);

Widget w1;
Widget w2;

w1.setWindowTitle("Widget 1 - Look I have Changed");
w2.setWindowTitle("Widget 2 - Look I have Changed");

w1.setPartner(&w2);
w2.setPartner(&w1);

w1.showMaximized();

return app.exec();
}