问题描述
我使用Qt4 QPushButton
和QMenu
(由设置).发生一些不相关的事件时,我需要显示此菜单.
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中显示菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!