tags:

views:

22

answers:

2

Hi,

I want to create a drop down list in PyQt4, that executes an action when an element is selected. Also, some options may not be available at some time. They should still be in the list, but greyed out.

I tried attaching a menu to a QToolButton, but I can not even see the menu. How is it done?

Thanks! Nathan

A: 

Use a popup. You can trigger a popup anywhere, using the QMenu.exec_ method and passing the point at which you want the menu to appear.

I created a button that remembered where it was clicked, and connected that to the method to create and display the popup.

class MemoryButton(QPushButton):
    def __init__(self, *args, **kw):
        QPushButton.__init__(self, *args, **kw)
        self.last_mouse_pos = None

    def mousePressEvent(self, event):
        self.last_mouse_pos = event.pos()
        QPushButton.mousePressEvent(self, event)

    def mouseReleaseEvent(self, event):
        self.last_mouse_pos = event.pos()
        QPushButton.mouseReleaseEvent(self, event)

    def get_last_pos(self):
        if self.last_mouse_pos:
            return self.mapToGlobal(self.last_mouse_pos)
        else:
            return None

button = MemoryButton("Click Me!")

def popup_menu():
    popup = QMenu()
    menu = popup.addMenu("Do Action")

    def _action(check):
        print "Action Clicked!"

    menu.addAction("Action").triggered.connect(_action)                                                             
    popup.exec_(button.get_last_pos())

button.clicked.connect(popup_menu)
Chris B.
A: 

QToolButton has ToolButtonPopupMode enum that controls how it handles menus and multiple actions. When set to QToolButton::MenuButtonPopup, it will display the arrow that is typical of buttons that have menu options.

To use it set the appropriate popup mode and then you can either add a menu to the QToolButton using setMenu or you can add actions using addAction. QToolButton should then respond as expected to clicks on the menu, whether Action generated or an actual QMenu.

Kaleb Pederson