简体   繁体   English

Qt4小部件:实现等待功能而不阻塞小部件

[英]Qt4 Widget: implementing a wait function without blocking the widget

I'm writing a simple game in C++ using the (awesome) Qt4 libraries. 我正在使用(出色的)Qt4库在C ++中编写一个简单的游戏。 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. 该窗口小部件提供(其中包括)2种方法,这些方法可更改窗口小部件对用户输入的响应方式,例如鼠标移动,单击等。让我们将这些函数称为fun1()fun2()以避免上下文。 All these functions do, is toggle some internal variables in the widget which are checked by all the event-functions (eg mouseMoveEvent() ). 所有这些功能都可以在窗口小部件中切换一些内部变量,这些内部变量将由所有事件功能(例如mouseMoveEvent() )进行检查。 When fun1() is called, the user is expected to perform a move by interacting with the widget and clicking somewhere. 调用fun1() ,希望用户通过与小部件进行交互并单击某个位置来执行移动。 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. 现在,包含此小部件的主类有时会调用fun1()fun2() 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. 我必须实现一些(优雅的)方法,以确保主循环位于fun1()的末尾,直到移动完成为止。

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? 在保持GUI的响应能力(即响应用户交互wait()同时,应如何实现wait()

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() . 只有收到此信号后,我才调用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. 原来,我已经尝试过的解决方案确实有效,但是我从主窗口的构造函数中愚蠢地调用了fun1()fun2() Therefore, app.exec() was never called because of the waiting-function and events were not handled. 因此,由于等待功能而从未调用app.exec() ,并且未处理事件。

The working implementation of wait() for those interested is: 对感兴趣的人来说, wait()的有效实现是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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