C++ (Qt)#include <QMenu>#include <QMouseEvent>#include <QKeyEvent> class QUCheckableMenu : public QMenu{Q_OBJECTpublic: QUCheckableMenu( QWidget* parent = 0 ); virtual ~QUCheckableMenu() {}protected: void mouseReleaseEvent( QMouseEvent* e ); void keyPressEvent( QKeyEvent* e ); void setVisible( bool set ); private: bool skip_hide_;}; QUCheckableMenu::QUCheckableMenu( QWidget* parent ): QMenu( parent ), skip_hide_( false ){ setCheckable( true );} void QUCheckableMenu::mouseReleaseEvent( QMouseEvent* e ){ if( rect().contains( e->pos() ) && ( e->state() & Qt::ControlButton ) ) skip_hide_ = true; QMenu::mouseReleaseEvent( e );} void QUCheckableMenu::keyPressEvent( QKeyEvent* e ){ QMenu::keyPressEvent( e ); if( ( e->key() == Qt::Key_Space || e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter ) && ( e->state() & Qt::ControlButton ) ) skip_hide_ = true;} void QUCheckableMenu::setVisible( bool set ){ if( set ) { QMenu::setVisible( set ); } else { if( !skip_hide_ ) QMenu::setVisible( set ); skip_hide_ = false; }}
void QUCheckableMenu::mouseReleaseEvent( QMouseEvent* e ){ QAction *action = actionAt(e->pos()); if (action) action->trigger(); else QMenu::mouseReleaseEvent( e );}
Pythonclass ChechableMenu(QtGui.QMenu): def __init__(self): QtGui.QMenu.__init__(self) self.installEventFilter(self) self.visible_flag = True def setVisible(self, mode): #print 'SetVisible( ' + str(mode) + ' )' + ' flag = ' + str(self.visible_flag) QtGui.QMenu.setVisible(self, mode | self.visible_flag) def eventFilter(self, object, event): event_type = event.type() if event_type in (2, 3, 4): print 'Mouse ' + str(event_type) self.visible_flag = True return QtGui.QWidget.eventFilter(self, object, event) elif event_type == 19: print 'Close' self.visible_flag = False return True else: return QtGui.QWidget.eventFilter(self, object, event)