How to show the menu in QPushButton without blocking?

一曲冷凌霜 提交于 2019-12-11 12:42:28

问题


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

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?


回答1:


QMenu is QWidget. So you can call move() before show().




回答2:


You can use

void QMenu::popup ( const QPoint & p, QAction * atAction = 0 )

So

Displays the menu so that the action atAction will be at the specified global position p. To translate a widget's local coordinates into global coordinates, use QWidget::mapToGlobal().




回答3:


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

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);
} 


来源:https://stackoverflow.com/questions/22948145/how-to-show-the-menu-in-qpushbutton-without-blocking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!