I'm trying to add sub-menu items to a menu that linked to a toolbar icon. It's probably best to show what result I'm getting currently, then reference the code:
The code is coming from a plugin class:
class SandBox2:
def __init__(self, iface):
self.iface = iface
self.plugin_dir = os.path.dirname(os.path.realpath(__file__))
self.actions = []
def initGui(self):
self.toolbar = self.iface.addToolBar("Sandbox2")
self.toolbar.setObjectName("Sandbox2")
self.SetupSubMenu = QAction((QIcon("C:/Users/Rudy/.qgis2/python/plugins/arcLensStandard/icons/new.png")), "Sub-Item 1-1",self.iface.mainWindow())
self.submenu_11 = QMenu(self.iface.mainWindow())
self.submenu_11.addAction(self.SetupSubMenu)
self.SetupSubMenu.triggered.connect(self.runMsg1)
self.SetupMainMenuItem = QAction((QIcon("C:/Users/Rudy/.qgis2/python/plugins/arcLensStandard/icons/item_one.png")), "First Menu Item", self.iface.mainWindow())
self.Menu1 = QMenu(self.iface.mainWindow())
self.Menu1.addAction(self.SetupMainMenuItem)
self.Menu1.addMenu(self.submenu_11)
self.toolButton = QToolButton()
self.toolButton.setIcon(QIcon("C:/Users/Rudy/.qgis2/python/plugins/arcLensStandard/icons/adddata.png"))
self.toolButton.setMenu(self.Menu1)
self.toolButton.setPopupMode(QToolButton.InstantPopup)
self.toolbar.addWidget(self.toolButton)
def runMsg1(self):
QMessageBox.information(self.iface.mainWindow(), "Message",
"Sub-Item 1-1 Message", QMessageBox.Ok)
What I want to see is the right-facing caret symbol on the same line as the "First Menu Item" string, instead of appearing on a blank line after the string. The statement that's adding the sub-menu is:
self.Menu1.addMenu(self.submenu_11)
and that's where the blank line gets inserted (apparently).
Answer
You can assign a name to Menu1
(e.g. first_menu
) and then call this when adding your action for your submenu:
def initGui(self):
self.toolbar = self.iface.addToolBar("Sandbox2")
self.toolbar.setObjectName("Sandbox2")
self.SetupSubMenu = QAction((QIcon("C:/Users/Rudy/.qgis2/python/plugins/arcLensStandard/icons/new.png")), "Sub-Item 1-1",self.iface.mainWindow())
self.SetupSubMenu.triggered.connect(self.runMsg1)
self.Menu1 = QMenu(self.iface.mainWindow())
# Here we assign the name for the first menu
first_menu = self.Menu1.addMenu(QIcon("C:/Users/Rudy/.qgis2/python/plugins/arcLensStandard/icons/item_one.png"), "First Menu Item")
# Call first_menu to add the action for the submenu
first_menu.addAction(self.SetupSubMenu)
self.toolButton = QToolButton()
self.toolButton.setIcon(QIcon("C:/Users/Rudy/.qgis2/python/plugins/arcLensStandard/icons/adddata.png"))
self.toolButton.setMenu(self.Menu1)
self.toolButton.setPopupMode(QToolButton.InstantPopup)
self.toolbar.addWidget(self.toolButton)
No comments:
Post a Comment