3

I created the simple frame .UI file, compiled with pyuic4, and tried the ShapeViewer.py to load the shapefile "world_borders.shp". However, the map is always loaded in different random colors every time I rerun the python program. Why is this so? I tried loading the map in QGIS program & it loaded consistently with the same colors.

#! /usr/bin/env python

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
import sys, os

# Import our GUI.
from shapeviewer_gui import Ui_MainWindow

class ShapeViewer(QMainWindow, Ui_MainWindow):
  def __init__(self):
    QMainWindow.__init__(self)

    # Required by Qt4 to initialize the UI.
    self.setupUi(self)
    self.layers = []

    # Set the title for the app.
    self.setWindowTitle("ShapeViewer")

    # Create the map canvas.
    self.canvas = QgsMapCanvas()
    self.canvas.useImageToRender(False)

    # Set the background color to white.
    self.canvas.setCanvasColor(Qt.white)
    self.canvas.enableAntiAliasing(True)
    self.canvas.show()

    # Lay our widgets out in the main window using a vertical box layout.
    self.layout = QVBoxLayout(self.frame)
    self.layout.addWidget(self.canvas)

    actionZoomIn = QAction(QString("Zoom in"), self)
    actionZoomOut = QAction(QString("Zoom out"), self)
    actionPan = QAction(QString("Pan"), self)

    actionZoomIn.setCheckable(True)
    actionZoomOut.setCheckable(True)
    actionPan.setCheckable(True)

    self.toolbar = self.addToolBar("Canvas actions")
    self.toolbar.addAction(actionZoomIn)
    self.toolbar.addAction(actionZoomOut)
    self.toolbar.addAction(actionPan)

    # Create the map tools.
    self.toolPan = QgsMapToolPan(self.canvas)
    self.toolPan.setAction(actionPan)
    self.toolZoomIn = QgsMapToolZoom(self.canvas, False) # false = in
    self.toolZoomIn.setAction(actionZoomIn)
    self.toolZoomOut = QgsMapToolZoom(self.canvas, True) # true = out
    self.toolZoomOut.setAction(actionZoomOut)

    self.pan()

    # Layout is set - open a layer.
    # Add an OGR layer to the map.
    self.Add_Map_Layer("qgis_data/world_borders.shp")

    self.connect(actionZoomIn, SIGNAL("triggered()"), self.zoomIn)
    self.connect(actionZoomOut, SIGNAL("triggered()"), self.zoomOut)
    self.connect(actionPan, SIGNAL("triggered()"), self.pan)

  def zoomIn(self):
    self.canvas.setMapTool(self.toolZoomIn)

  def zoomOut(self):
    self.canvas.setMapTool(self.toolZoomOut)

  def pan(self):
    self.canvas.setMapTool(self.toolPan)

  def Add_Map_Layer(self, mapFileName):
    # Add the layer
    if mapFileName == "":
      layer = QgsVectorLayer()
    else:
      layer = QgsVectorLayer(os.path.abspath(mapFileName), mapFileName[mapFileName.rfind("/")+1:-4], "ogr")

    if not layer.isValid():
      print "Layer failed to load! :("
      return

    # Add layer to the registry
    QgsMapLayerRegistry.instance().addMapLayer(layer);

    # Set extent to the extent of our layer
    self.canvas.setExtent(layer.extent())

    # Set up the map canvas layer set
    self.layers.append( QgsMapCanvasLayer(layer) )
    self.canvas.setLayerSet(self.layers)

def main(argv):
  # create Qt application
  app = QApplication(argv)

  # Environment variable QGISHOME must be set to the install directory
  # before running the application
  qgis_prefix = os.getenv("QGISHOME")
  if qgis_prefix == None:
    qgis_prefix = "/usr"

  # Initialize qgis libraries
  QgsApplication.setPrefixPath(qgis_prefix, True)
  QgsApplication.initQgis()

  # create main window
  wnd = ShapeViewer()
  # Move the app window to upper left
  wnd.move(100,100)
  wnd.show()

  # run!
  retval = app.exec_()

  # exit
  QgsApplication.exitQgis()
  sys.exit(retval)

if __name__ == "__main__":
  main(sys.argv)

1 Answer 1

1

This is because without having a default style set QGIS doesn't know how to display the layer and just picks a random fill/line/point colour.

If you are loading it in QGIS and getting the same colour changes are you have saved a default style for the layer and QGIS is loading that.

You can use layer.loadNamedStyle(your.qml) to load a style for the layer. http://www.qgis.org/api/classQgsMapLayer.html#a6b117fdc1a090d014374a6981405d1ea

4
  • Thanks for the quick reply. How do I create my own style to prevent this in my standalone python program?
    – Whospal
    Commented Nov 29, 2012 at 10:05
  • Style the layer in QGIS and save the style from the Layer Properties dialog. The other option is to set color/style when you add the layer in ShapeViewer.py.
    – gsherman
    Commented Mar 2, 2013 at 17:35
  • link not working now can you update it?.
    – user41010
    Commented Nov 24, 2014 at 5:20
  • @anonymus I just clicked on the link provided by Nathan and it worked fine
    – PolyGeo
    Commented Nov 24, 2014 at 5:23

Your Answer

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

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