2

I am working on a standalone Python script for loading shapefile layers into an application window with my central widget being canvas. The previous code I had written is almost identical to the code pasted below except for the last bit. if name=="main" was substituted with a def main():. The previous code that used with def main(): successfully pulled up the main window and displayed my layers and tool bar accordingly; however, some of the buttons on my tool bar weren't working. I'm assuming this is because this application shouldn't be running on def main():, but rather, should run in a "main loop".

Once I've substituted def main(): with this loop, my program no longer pulls up an application window or anything (I also don't receive any errors). I'm unfamiliar with the usage of if__name__=="main", am I employing it incorrectly?

Here is an abridged version of my code:


class MyWnd(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        # supply path to qgis install location
        QgsApplication.setPrefixPath("/usr", True)

        # initialize application
        QgsApplication.initQgis()

        self.canvas_layers = []

        # set the title for the application
        self.setWindowTitle("ENC Viewer")

        # create the canvas
        self.canvas = QgsMapCanvas()
        self.canvas.setCanvasColor(Qt.white)
        self.canvas.enableAntiAliasing(True)

        # add layers
        vlayer = QgsVectorLayer("/home/cassandra/desktop/file_formats/Shapefiles/US6SP10M-BUAARE.shp", "BUAARE Layer", "ogr")
        vlayer2 = QgsVectorLayer("/home/cassandra/desktop/file_formats/Shapefiles/US6SP10M-LNDARE.shp", "LNDARE Layer", "ogr")
        vlayer3 =  QgsVectorLayer("/home/cassandra/desktop/file_formats/Shapefiles/US6SP10M-SOUNDG.shp", "SOUNDG Layer", "ogr")
        layers = [vlayer, vlayer2, vlayer3]

        # create rectangle object
        extent = QgsRectangle()
        extent.setMinimal()
        extent.scale(1.1)

        # traverse each layer in the list of layers, may be one layer
        for layer in layers:

        # register each layer
        QgsMapLayerRegistry.instance().addMapLayer(layer)

        # combine the extent of each layer to the rectangle object
        extent.combineExtentWith(layer.extent())
        self.canvas_layers.append(QgsMapCanvasLayer(layer))

    # set the extent of the canvas
    self.canvas.setExtent(extent)

    # provide set of layers to display on canvas
    self.canvas.setLayerSet(self.canvas_layers)

    # set centra lwidget to the canvas app
    self.setCentralWidget(self.canvas)

    actionPoint = QAction("Point", self)
    actionPoly = QAction("Polygon", self)

    actionPoint.setCheckable(True)
    actionPoly.setCheckable(True)

    self.connect(actionPoint, SIGNAL("triggered()"), self.point)
    self.connect(actionPoly, SIGNAL("triggered()"), self.poly)

    self.toolbar.addAction(actionPoint)
    self.toolbar.addAction(actionPoly)

    # 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.toolPoint = PointMapTool(self.canvas)
    self.toolPoint.setAction(actionPoint)

    self.toolPoly = PolyMapTool(self.canvas)
    self.toolPoly.setAction(actionPoly)

    self.point()
    self.poly()

    def point(self):
      self.canvas.setMapTool(self.toolPoint)

    def poly(self):
        self.canvas.setMapTool(self.toolPoly)


class PolyMapTool(QgsMapToolEmitPoint):
    def __init__(self, canvas):
        self.canvas = canvas

        QgsMapToolEmitPoint.__init__(self, self.canvas)
        self.rubberband = QgsRubberBand(self.canvas, QGis.Polygon)
        self.rubberband.setColor(Qt.red)
        self.rubberband.setWidth(1)
        self.point = None
        self.points = []

        def canvasPressEvent(self, e):
            self.point = self.toMapCoordinates(e.pos())
            m = QgsVertexMarker(self.canvas)
            m.setCenter(self.point)
            m.setColor(QColor(0, 255, 0))
            m.setIconSize(5)
            m.setIconType(QgsVertexMarker.ICON_BOX)
            m.setPenWidth(3)
            self.points.append(self.point)
            self.isEmittingPoint = True
            self.showPoly()

        def showPoly(self):
            self.rubberband.reset(QGis.Polygon)
            for point in self.points[:-1]:
                self.rubberband.addPoint(point, False)
                self.rubberband.addPoint(self.points[-1], True)
                self.rubberband.show()


class PointMapTool(QgsMapToolEmitPoint):
    def __init__(self, canvas):
        self.canvas = canvas

        QgsMapToolEmitPoint.__init__(self, self.canvas)

        self.point = None

        def canvasPressEvent(self, e):
            self.point = self.toMapCoordinates(e.pos())
            print self.point.x(), self.point.y()
            m = QgsVertexMarker(self.canvas)
            m.setCenter(self.point)
            m.setColor(QColor(0, 255, 0))
            m.setIconSize(5)
            m.setIconType(QgsVertexMarker.ICON_BOX, ICON_X)
            m.setPenWidth(3)


class MainApp(QApplication):
    def __init__(self):
        QApplication.__init__(self, [], True)
        wdg = MyWnd()
        wdg.show()
        self.exec_()

if __name__=="main":
    import sys
    app = MainApp()
4

It looks like your issue might be caused by as simple syntax error.

The correct syntax is if __name__ == '__main__': (with double underscores around main)

That if statement is essentially used to check whether the file is being executed as a standalone script or if it has been imported by some other python script. Anything inside the if statement will only be executed if the file is being run as a standalone script.

  • Well that's embarrassing, thanks! Your explanation is much clearer than the others I've come across. – GreyEyedPallas Jun 23 '16 at 15:41

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.