alignmentlabelpyqt4qgisatlas

PYQGIS Composer Label Alignment


I've been working on a bit of script for QGIS in order to automate atlas generation through the composer.

The only issue I've had is I can't align the composer label correctly. Here's the code sample:

composerLabel = QgsComposerLabel(c)
newFont = QFont("times", 40)
composerLabel.setFont(newFont) 
composerLabel.setText("Hello world")
composerLabel.adjustSizeToText()
composerLabel.setItemPosition(c.paperWidth() / 2,0)

composerLabel.setHAlign(Qt.AlignCenter)

c.addItem(composerLabel)

Here's what the image output looks like

I've had a look at the API and scowered PYQGIS forums but no-one else sounds like they're having similar alignment issues. Can anyone see where I might be going wrong?


Solution

  • You only need add the ItemPositionMode in the setItemPosition method.

    # add label
    composerLabel = QgsComposerLabel(c)
    newFont = QFont("times", 40)
    composerLabel.setFont(newFont) 
    composerLabel.setText("Hello world")
    composerLabel.adjustSizeToText()
    composerLabel.setItemPosition(c.paperWidth() / 2,0,QgsComposerItem.UpperMiddle)
    
    composerLabel.setHAlign(Qt.AlignCenter)
    
    c.addComposerLabel(composerLabel)