简体   繁体   中英

Qt4 Widget: implementing a wait function without blocking the widget

I'm writing a simple game in C++ using the (awesome) Qt4 libraries. For a while now, I'm having trouble with the following:

The widget provides (among others) 2 methods, that change the way the widget responds to user input like mouse-movement an clicks etc. Let's call these functions fun1() and fun2() to avoid context. All these functions do, is toggle some internal variables in the widget which are checked by all the event-functions (eg mouseMoveEvent() ). When fun1() is called, the user is expected to perform a move by interacting with the widget and clicking somewhere. The widget checks whether his move was valid and if so, applies his move to the current gamestate.

Now, the main class containing this widget at some point calls fun1() and fun2() subsequently. I have to implement something (elegant) to ensure that the main loop sits around at the end of fun1() until the move has been completed.

void Widget::fun1()
{
    // Set some members in order to tell the Widget how to respond to events
    // ...
    wait(); // wait for the move to be completed before returning from fun1()
}

How should wait() be implemented whilst maintaining the responsiveness of the GUI, ie whilst responding to user interaction?

In the past, I resolved this issue by letting the widget's parent wait for the widget to emit a signal that notifies it has finished. Only when this signal was recieved did I call fun2() . Though this might work fine, it bothers me that it makes the act of waiting the responsibility of the class using the widget instead of the widget itself.

Any suggestions would be very helpful!

First of all, let me apologize for answering my own question. It turns out that the solutions that I had already tried did work, but that I stupidly called fun1() and fun2() from the constructor of the main window. Therefore, app.exec() was never called because of the waiting-function and events were not handled.

The working implementation of wait() for those interested is:

void Widget::wait()
{
    static QEventLoop loop;
    connect(this, SIGNAL(done()), &loop, SLOT(quit()));
    loop.exec();
}

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