我需要确定我的Qt 4.4.1应用程序何时获得焦点.
我提出了两种可能的解决方案,但它们都不能完全按照我的意愿工作.
在第一个可能的解决方案中,我将来自qApp的focusChanged()信号连接到SLOT.在插槽中,我检查'旧'指针.如果它为'0',那么我知道我们已经切换到这个应用程序,我做我想做的事情.这似乎是让应用程序检测这里介绍的两个解决方案焦点的最可靠方法,但是遇到了下面描述的问题.
在第二种可能的解决方案中,我覆盖了'focusInEvent()'例程,如果原因是'ActiveWindowFocusReason',那就做我想要的.
在这两种解决方案中,代码都是在我不希望的时候执行的.
例如,我有这个代码覆盖focusInEvent()例程:
void
ApplicationWindow::focusInEvent( QFocusEvent* p_event )
{
Qt::FocusReason reason = p_event->reason();
if( reason == Qt::ActiveWindowFocusReason &&
hasNewUpstreamData() )
{
switch( QMessageBox::warning( this, "New Upstream Data Found!",
"New upstream data exists!\n"
"Do you want to refresh this simulation?",
"&Yes", "&No", 0, 0, 1 ) )
{
case 0: // Yes
refreshSimulation();
break;
case 1: // No
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
执行此操作时,将显示QMessageBox对话框.但是,当通过按"是"或"否"关闭对话框时,会立即再次调用此函数,因为我认为焦点在此时使用ActiveWindowFocusReason更改回应用程序窗口.显然我不希望这种情况发生.
同样,如果用户正在使用应用程序打开和关闭对话框和窗口等,我不希望激活此例程.注意:我不确定此例程被激活的情况,因为我已经尝试了一下,并且它不会发生在所有窗口和对话框中,尽管它至少发生在示例代码中显示的那个.
如果应用程序是从该应用程序外部关注的,而不是主窗口从其他对话框窗口聚焦,我只想激活它.
这可能吗?如何才能做到这一点?
感谢您提供任何信息,因为这对我们的应用程序非常重要.
雷蒙德.
我认为你需要跟踪QEvent :: ApplicationActivate事件.
您可以在QApplication实例上放置一个事件过滤器,然后查找它.
bool
ApplicationWindow::eventFilter( QObject * watched, QEvent * event )
{
if ( watched != qApp )
goto finished;
if ( event->type() != QEvent::ApplicationActivate )
goto finished;
// Invariant: we are now looking at an application activate event for
// the application object
if ( !hasNewUpstreamData() )
goto finished;
QMessageBox::StandardButton response =
QMessageBox::warning( this, "New Upstream Data Found!",
"New upstream data exists!\n"
"Do you want to refresh this simulation?",
QMessageBox::Yes | QMessageBox::No) );
if ( response == QMessageBox::Yes )
refreshSimulation();
finished:
return <The-Superclass-here>::eventFilter( watched, event );
}
ApplicationWindow::ApplicationWindow(...)
{
if (qApp)
qApp->installEventFilter( this );
...
}
Run Code Online (Sandbox Code Playgroud)