I have something like this:

class Main(QWidget):
    def __init__(self):
        super().__init__()

    def init_gui(self):
        self.layout = QGridLayout()
        self.setLayout(self.layout)
        self.button_sett()
        self.show()
    def button_sett(self):
        button = QPushButton()
        menu = QMenu()
        menu.addAction("Settings", self.switch_page) 
        menu.addAction("About", self.switch_page)
        button.setMenu(menu)

Can I somehow tell a function the textContent of an action?

Like this:

def switch_page():
    if textContent == "Settings":
    .......

Is there a better way? I don't want to write functions like switch_page_to_settings and switch_page_to_about, because I have more actions on the button.

1 Answers

0
Alex Hall On Best Solutions
def button_sett(self):
    button = QPushButton()
    menu = QMenu()

    def action(title):
        menu.addAction(title, lambda: self.switch_page(title))

    action("Settings")
    action("About")

    button.setMenu(menu)

def switch_page(self, title):
    if title == "Settings":
        pass  # TODO

The lambda is equivalent to:

    def action(title):
        def switch():
            self.switch_page(title)

        menu.addAction(title, switch)