我已经为我的应用程序设置了一个系统托盘图标,并为其附加了一个简单的上下文菜单。如果我右键单击该图标以调出上下文菜单,它就可以正常工作。如果我然后单击失去应用程序焦点的某个地方(例如任务栏上的其他地方或另一个应用程序),上下文菜单不会被删除并且在单击时仍会触发正确的操作。但是,如果我单击主应用程序,上下文菜单会按预期消失。
这是创建托盘图标和上下文菜单的相关代码 -
actionExit = new QAction( "Exit", this );
connect( actionExit, SIGNAL( triggered() ), this, SLOT( ExitClient() ));
myTrayIconMenu = new QMenu( this );
myTrayIconMenu->addAction( actionExit );
trayIcon = new QSystemTrayIcon( icon, this );
trayIcon->setContextMenu( myTrayIconMenu );
connect( systrayIcon, SIGNAL( activated( QSystemTrayIcon::ActivationReason )),
this, SLOT( ToggleVisibility( QSystemTrayIcon::ActivationReason )));
trayIcon->show( );
我是否需要添加自己的代码来测试应用是否失去焦点,以便我可以手动隐藏上下文菜单?我原以为会内置此功能。
[问题出现在 Windows 7 中,通过 Qt 插件使用 Visual Studio 2010 Pro 编译 - 我没有在任何其他操作系统下测试过]
我在 API 文档中注意到了这一点 -
Note: The system tray icon does not take ownership of the menu. You must ensure that it is deleted at the appropriate time by, for example, creating the menu with a suitable parent object.
如果我用
myTrayIconMenu = new QMenu( );
代替
myTrayIconMenu = new QMenu( this );
当应用程序失去焦点时,上下文菜单将被删除。但随后我需要注意手动删除上下文菜单。
其他人是如何处理这种情况的?
最佳答案
在您的 QApplication 派生类中实现 QSystemTrayIcon 而不是某些 QWidget 可以解决此问题。
主要.cpp:
int main(int argc, char *argv[])
{
return TestApp(argc, argv).exec();
}
测试应用.cpp:
TestApp::TestApp(int &argc, char **argv) :
QApplication(argc, argv)
{
quitAction = new QAction("quit", this);
connect(quitAction, SIGNAL(triggered()), this, SLOT(quit()));
systemTrayMenu = new QMenu("tray menu");
systemTrayMenu->addAction(quitAction);
trayIcon = new QSystemTrayIcon( this);
trayIcon -> setToolTip("test app");
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
trayIcon -> setContextMenu(systemTrayMenu);
trayIcon -> show();
}
关于windows - 当应用程序失去焦点时,Qt 系统托盘上下文菜单仍然存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6115766/