2

I need help. I'm trying to open 1 of 2 possible windows on start. Program decide which window will open on screen dimensions.

#include <QApplication> #include <QDesktopWidget> #include "mainwindow.h" #include "vincellform.h" #include <QDebug> int main(int argc, char *argv[]) { QApplication a(argc, argv); QDesktopWidget mydesk; if (mydesk.screenGeometry().width() == 800 && mydesk.screenGeometry().height() == 480) { VincellForm vf; vf.show(); } else { MainWindow w; w.show(); } return a.exec(); } 

I think that this code is correct, but it isn't. If I'm on different screen (1280*1024 I think) program goes to else part (MainWindow w; w.show();) and then goes to return, but no window is opened. But if I changed a code to:

#include <QApplication> #include <QDesktopWidget> #include "mainwindow.h" #include "vincellform.h" #include <QDebug> int main(int argc, char *argv[]) { QApplication a(argc, argv); QDesktopWidget mydesk; if (mydesk.screenGeometry().width() == 800 && mydesk.screenGeometry().height() == 480) { VincellForm vf; vf.show(); } MainWindow w; w.show(); return a.exec(); } 

it runs perfectly (MainWindow will open after return). I can't even imagine where the problem can be... Thank you very much

1 Answer 1

4

You're defining the window variables locally in the if and else blocks. This means the windows are destroyed immediately after they're shown.

You have two solutions. If you don't mind creating both windows, but only showing one, do this:

int main(int argc, char *argv[]) { QApplication a(argc, argv); QDesktopWidget mydesk; VincellForm vf; MainWindow w; if (mydesk.screenGeometry().width() == 800 && mydesk.screenGeometry().height() == 480) { vf.show(); } else { w.show(); } return a.exec(); } 

If you only want one of them created, you'll have to resort to dynamic allocation:

int main(int argc, char *argv[]) { QApplication a(argc, argv); QDesktopWidget mydesk; std::unique_ptr<VincellForm> vf; std::unique_ptr<MainWindow> w; if (mydesk.screenGeometry().width() == 800 && mydesk.screenGeometry().height() == 480) { vf.reset(new VincellForm); vf->show(); } else { w.reset(new MainWindow); w->show(); } return a.exec(); } 

Note: std::unique_ptr comes from C++11. If you don't have this yet, use raw pointers instead a delete manually at program end.

Sign up to request clarification or add additional context in comments.

3 Comments

You don't need raw pointers, Qt comes with a number of auto pointers. QPointer is the most appropriate in this case.
How about std::unique_ptr<QWindow>w = (screenGeometryTest ? new VincellForm() : new MainWindow); ? They share a base class, after all.
@RobbieE No, QPointer is not what you need here. Quoting the destructor docs from the link you posted: "Just like a normal pointer, destroying a guarded pointer does not destroy the object being pointed to."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.