79294362

Date: 2024-12-19 12:58:22
Score: 0.5
Natty:
Report link

This is my current workaround - not an answer I like, because it doesn't use the actions directly:

import sys
import os
import gi

gi.require_version("Gtk", "3.0")
from gi.repository import GLib, Gio, Gtk

_curr_dir = os.path.split(__file__)[0]

# This would typically be its own file
MENU_XML = """
<?xml version="1.0" encoding="UTF-8"?>
<interface>
  <object class="GtkMenu" id="context_menu">
    <child>
      <object class="GtkMenuItem" id="option1">
        <property name="label">Option 1</property>
        <signal name="activate" handler="on_option1_activated"/>
      </object>
    </child>
    <child>
      <object class="GtkMenuItem" id="option2">
        <property name="label">Option 2</property>
        <signal name="activate" handler="on_option2_activated"/>
      </object>
    </child>
  </object>
</interface>
"""


class RightClickMenu(Gtk.Window):
    def __init__(self):
        super().__init__(title="Right-Click Context Menu")

        self.set_default_size(400, 300)
        self.connect("destroy", Gtk.main_quit)

        # Load the UI from the Glade file
        builder = Gtk.Builder()
        builder = Gtk.Builder.new_from_string(MENU_XML, -1)

        # Get the context menu defined in the XML
        self.context_menu = builder.get_object("context_menu")

        # Connect the signals for menu item activation
        builder.connect_signals(self)

        # Add a simple label
        self.label = Gtk.Label(label="Right-click to open context menu")
        self.add(self.label)

        # Connect the button press event (right-click)
        self.connect("button-press-event", self.on_right_click)

    def on_right_click(self, widget, event):
        # Check if it's the right-click (button 3)
        if event.button == 3:
            # Show the context menu
            # self.context_menu.popup(None, None, None, None, event.button, event.time)
            self.context_menu.show_all()
            self.context_menu.popup_at_pointer(event)

    def on_option1_activated(self, widget):
        print("Option 1 selected")

    def on_option2_activated(self, widget):
        print("Option 2 selected")

if __name__ == "__main__":
    win = RightClickMenu()
    win.show_all()
    Gtk.main()
Reasons:
  • Blacklisted phrase (1): not an answer
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: DobbyTheElf