简体   繁体   中英

Decide which Window open in QT on start

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM