2

I've successfully created a script that adds a button to the plugin toolbar in QGIS, by running the script in the python console.

Here is my code:

import webbrowser
icon_path = MyPath

def open_url():
webbrowser.open(MyURL)

action = QAction(name)
action.triggered.connect(open_url)
action.setIcon(QIcon(icon_path))
iface.addToolBarIcon(action)

I have read that you can make QGIS to add the button when a certain QGIS project is loaded by using 'Project properties' -> 'Macros'.

Though, This won't work for me.

What I have tried is...:

import webbrowser
from qgis.PyQt.QtGui import *
from qgis.PyQt.QtWidgets import *
from qgis.utils import iface

def openProject():

url = 'https://google.dk'

def show_url():
    iface.messageBar().pushMessage()
    webbrowser.open(url, new=1)

action = QAction('Show Time')
action.triggered.connect(show_url)
action.setIcon(QIcon(MyPath)
iface.addToolBarIcon(action)

Can anybode figure out what I am missing in the code for make the Macro work out well?

1 Answer 1

3

Did you check that macro execution is enabled in QGIS settings?

enter image description here

Besides, there's some problem with your code:

  • Wrong indentation (after def openProject():)
  • Missing parenthesis action.setIcon(QIcon(MyPath))
  • Missing parameter iface.messageBar().pushMessage(f"Open {url}")
  • Undefined variable MyPath
  • You may want to remove the action when the project is closed

Here is what your macro script may look like

import webbrowser
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction
from qgis.utils import iface

url = 'https://google.dk'
iconPath = ':/images/themes/default/mIconWms.svg'

def show_url():
    iface.messageBar().pushMessage("Showing URL")
    webbrowser.open(url, new=1)

action = QAction(QIcon(iconPath), 'Show Time')
action.triggered.connect(show_url)

def openProject():
    iface.addToolBarIcon(action)

def saveProject():
    pass

def closeProject():
    action.deleteLater()

1
  • Thank you so much! Works perfect! Best, Kristoffer
    – kwiwe
    Feb 20, 2020 at 9:59

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.