4

I am thinking about a new QGIS plugin I'm going to do in near future.

So, I have some things, that could be hard for me. One of them is to making the plugin icon active when I click it.

For example, when I click on the "identify" tool in QGIS, it becomes active, but when I press the "pan" tool, the pan tool becomes active and the identify tool is no longer active.

I want do the same to my plugin icon.

Can you explain to me a little bit about how I'm supposed to do that?

1

1 Answer 1

6

I found a better way (for me), so I post this for those who are might need it.

First thing you have to do is add one more parameter to default add_action function:

checkable=False,

and set checkable method to action function.

So it could looks like:

def add_action(
    self,
    icon_path,
    text,
    callback,
    checkable=False,
    enabled_flag=True,
    add_to_menu=True,
    add_to_toolbar=True,
    status_tip=None,
    whats_this=None,
    parent=None):

    icon = QIcon(icon_path)
    action = QAction(icon, text, parent)
    action.triggered.connect(callback)
    action.setEnabled(enabled_flag)
    action.setCheckable(checkable)

    if status_tip is not None:
        action.setStatusTip(status_tip)

    if whats_this is not None:
        action.setWhatsThis(whats_this)

    if add_to_toolbar:
        self.toolbar.addAction(action)

    if add_to_menu:
        self.iface.addPluginToVectorMenu(
            self.menu,
            action)

    self.actions.append(action)

    return action

So, according to this, when you gonna create action you have to add this line as well.

def initGui(self):    
        icon_path = 'your_path'
        self.add_action(
            icon_path,
            text=self.tr(u"Random text"),
            callback=self.function,
            checkable=True,
            parent=self.iface.mainWindow())

Second thing. Create file, where you will put your tool class.

tool.py

class Tool(QgsMapTool):
    def __init__(self, iface):
        canvas = iface.mapCanvas()
        QgsMapTool.__init__(self, canvas)
        self.canvas = canvas
        self.iface = iface

The last thing you have to do is create function in your main file to handle tool.

def function(self):
    self.tool = Tool(self.iface)
    self.tool.setAction(self.actions[0])
    self.iface.mapCanvas().setMapTool(self.tool)
    self.toolname = 'your_plugin_name'

If someone wants to know more I leave you with this link.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.