如何在不阻塞的情况下在QPushButton中显示菜单? [英] How to show the menu in QPushButton without blocking?

查看:297
本文介绍了如何在不阻塞的情况下在QPushButton中显示菜单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Qt4 QPushButtonQMenu(由设置).发生一些不相关的事件时,我需要显示此菜单.

I use Qt4 QPushButton with QMenu in it (set by setMenu()). I need to show this menu when some unrelated event occurs.

方法QPushButton::showMenu()可以执行此操作,但是它会阻塞,直到用户关闭菜单为止. QMenu::show()也会这样做,但是它会在屏幕的左上角显示菜单.

Method QPushButton::showMenu() does this, but it blocks until user closes the menu. QMenu::show() also does this, but it shows the menu in the top left corner of the screen.

如何以编程方式使菜单显示在正确的位置并且不受阻碍?

How can I programmatically make the menu show up properly positioned, and without blocking?

推荐答案

不,我不喜欢建议的解决方案,因为QPushButton应该管理菜单位置,而不是调用者.

No, I didn't like the suggested solutions, because QPushButton is supposed to manage the menu position, not the caller.

因此,我决定将鼠标向下/向上事件发布到此QPushButton小部件,以模拟用户的操作.这成功了.这是一种弥补Qt缺少功能的技术.

So I decided to post mouse down/up events to this QPushButton widget, simulating what the user does. This did the trick. This is a hack to compensate for the missing functionality in Qt.

void simulateMouseClick(QWidget *widget) {
  QPoint pos(widget->width()/2, widget->height()/2);
  QMouseEvent *evtDown = new QMouseEvent(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
  QMouseEvent *evtUp   = new QMouseEvent(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
  (void) QApplication::postEvent(widget, evtDown);
  (void) QApplication::postEvent(widget, evtUp);
} 

这篇关于如何在不阻塞的情况下在QPushButton中显示菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆