3

I've created a plugin icon which can toggle and is connected to the run() function. At the moment, whenever a user clicks on the icon, it executes the run() function.

How could I make it so that it only executes this function when its toggle state isChecked()?

A simple example:

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.addPluginToMenu(
            self.menu,
            action)

    self.actions.append(action)
    return action

def initGui(self):
    icon_path = ':/plugins/Example/icon.png'
    self.add_action(
        icon_path,
        text=self.tr(u'Example'),
        callback=self.run,
        checkable=True,
        parent=self.iface.mainWindow())

def run(self):
    print 'Plugin loaded.'
    #if checkable == True:
    #   print 'Checked'
    #else:
    #   print 'Unchecked'
0
4

It's a matter of writing a conditional inside the run() function.

QAction.triggered SIGNAL sends the checked state to its connected SLOTs. Add the checked parameter to run() and write a conditional based on that state.

Every button click will still execute the run() function, but you could choose what code you want to be executed for each state.

0
2

Just to add an alternative to @GermánCarrillo's answer, you can also name the action (e.g. self.iconAction = self.add_action(...)) and call this inside the run() function:

def initGui(self):
    icon_path = ':/plugins/Example/icon.png'
    self.iconAction = self.add_action(
        icon_path,
        text=self.tr(u'Example'),
        callback=self.run,
        checkable=True,
        parent=self.iface.mainWindow())

def run(self):
    print 'Plugin loaded.'
    if self.iconAction.isChecked():
        print 'Checked'
    else:
        print 'Unchecked'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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