0

I am new to QT GUI programming. I am trying to test switching two mainwindows continously by using show and hide.

I have created a simple code in main.cpp

      main(){
      QApplication a(argc , argv)
      Mainwinodw1 *window1 = new Mainwindow1();
      Mainwinodw1 *window2 = new Mainwindow2();

      for (;;)

        {
           window1->show();
           delay();
           window1->hide();

           window2->show();
           delay();
           window2->hide();

        }

      return a.exec();

      }

The test can display the windows only one time , but duirng the second iteration they dont show and hide.

Can somebody help to fix this.

VamsiKrishna Neelam
  • 103
  • 1
  • 1
  • 11

1 Answers1

0

Try to use Qt timers instead of hardcoded delay function.

main.cpp file:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Mainwindow1 *window1 = new Mainwindow1();
    Mainwindow2 *window2 = new Mainwindow2();
    WindowSwitcher ws(window1, window2, 2000);

    window1->show();

    return a.exec();
}

WindowSwitcher source code:

#include "windowswitcher.h"
#include <QTimer>

WindowSwitcher::WindowSwitcher(QMainWindow *w1, QMainWindow *w2, int delay) : QObject(), window1(w1), window2(w2)
{
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(switchWindow()));
    timer->start(delay);
}

void WindowSwitcher::switchWindow()
{
    if (window1->isVisible())
    {
        window1->hide();
        window2->show();
    }
    else
    {
        window1->show();
        window2->hide();
    }
}

WindowSwitcher header file:

#include <QObject>
#include <QMainWindow>

class WindowSwitcher : public QObject
{
    Q_OBJECT
public:
    explicit WindowSwitcher(QMainWindow *w1, QMainWindow *w2, int delay);

private:
    QMainWindow *window1;
    QMainWindow *window2;

public slots:
    void switchWindow();
};
ramzes2
  • 773
  • 5
  • 13