Search code examples
hoverqt5tooltipstatusbarpyside2

Can't set status bar from action hover slot in Pyside2/Qt 5


I want to show a tool tip in the status bar when hovering an action that is in a menu.

I am trying this since I could not find a way yet to show a tool tip when hovering.

However, I am not able to set the status bar from the hovering slot/event/callback either. Everything is being called, but it seems to have no effect, other than clearing the status bar.

Here is a minimum working example:

from PySide2.QtWidgets import QApplication, QMainWindow, QAction, QStatusBar

app = QApplication([])

# Create a main window
main_window = QMainWindow()

# Create an action
action = QAction("My Action", main_window)

# Add the action to the main window's menu bar
main_window.menuBar().addAction(action)

# Create a status bar
status_bar = QStatusBar(main_window)
status_bar.showMessage("Initialized.")
main_window.setStatusBar(status_bar)


# Define a function to update the status bar with tooltips
def update_status_bar():
    if action.isEnabled() and action.toolTip():
        status_bar.showMessage(action.toolTip())
    else:
        status_bar.clearMessage()


# Connect the hover events to the status bar update function
action.hovered.connect(update_status_bar)

# Show the main window
main_window.show()

# Run the application event loop
app.exec_()


Solution

  • The problem is caused by the fact that the hovered signal has precedence, and then it is emitted before the status tip event is triggered.

    Since the action's status tip is empty, the result is that, even if the status message is set by update_status_bar, it will instantly be cleared by the empty status tip.

    The simple solution is to explicitly set the status tip:

    action = QAction("My Action", main_window, statusTip="My Action")
    
    # alternatively:
    action = QAction("My Action", main_window)
    action.setStatusTip(action.text())