简体   繁体   中英

Qt: mainWindow->show(); does not show the mainWindow

In the code below, I create a window, invoke window.show() , but the window doesn't show up until after window->iterateSolution() is called. Almost as if, app.exec() is the function that shows the window. I'm very new to Qt so I have no idea what is going on.

#include <QtGui/QApplication>
#include <mainWindow.h>
#include <Cube.h>

mainWindow * newWindow;

int main(int argc, char *argv[]) {
    // initialize resources, if needed
    // Q_INIT_RESOURCE(resfile);

    QApplication app(argc, argv);
    newWindow = new mainWindow;
    newWindow->show();

    QString initialState = "YWOBYYBYYGRRGRRBWWYOOYGGRGGBBGYOOYOOWRRBBRBBWGOOGWWRWW";

    /* Construct cube, set state, and solve */
    Cube * cube = new Cube(initialState);
    QString solution = cube->solve();
    delete cube;
    newWindow->iterateSolution(solution);

    // create and show your widgets here

    return app.exec();
}

That's exactly what's happening.

Technically speaking, QMainWindow::show() does not make the window visible, it simply sets a flag in the window, and Qt will make it visible on the next iteration of the event loop.

Also, straight from Qt's documentation on QApplication::exec():

It is necessary to call this function to start event handling. The main event loop receives events from the window system and dispatches these to the application widgets.

Generally, no user interaction can take place before calling exec().

Sounds to me like you want to have a multi-threaded application. One thread should be responsible for the UI and another thread will solve the cube and post updates to the UI thread to display the progress. You can make the Cube object and the mainWindow object communicate using signals and slots to resolve cross-thread communication issues (see http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/ ).

Otherwise, if you put both operations on the same thread, the UI will "hang" as the main thread will not be able to process UI events (including the show event that you're specifically referring to in your question).

If this is overkill, you can just direct the application to explicitly process UI events by calling QApplication::process(...) before (and preferably during) any long-running synchronous operations. This will perform a one-time update to the UI so the user (and the OS) is aware that the application is not hung.

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