Search code examples
pythonpyqtpyqt4qgraphicsviewantialiasing

How to smoothing jagged edges on curved lines and diagonals on pyqt4?


I am drawing a line, but how keep the line ‘jag’ free and clean?

enter image description here

This is the code which draws the image above. Here we may notice the image is full of jagged edges.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

    def initUI(self):
        self.drawingPanel = DrawingPanel(self)

        verticalLayout = QtGui.QVBoxLayout( self )
        verticalLayout.addWidget( self.drawingPanel )

        self.setLayout( verticalLayout )
        self.resize( 400, 300 )

        self.setWindowTitle('Review')
        self.show()


class DrawingPanel(QtGui.QGraphicsView):

    def __init__( self, parent ):
        super( DrawingPanel, self ).__init__( parent )

        scene = QtGui.QGraphicsScene()
        self.setScene( scene )

        pencil = QtGui.QPen( QtCore.Qt.black, 2, QtCore.Qt.SolidLine )
        self.scene().addLine( QtCore.QLineF(0, 0, 300, 600), pencil )


def main():

    app = QtGui.QApplication( sys.argv )
    ex = Example()
    sys.exit( app.exec_() )


if __name__ == '__main__':
    main()

Here there is a zoom on the image:

enter image description here

Some other questions about it:

  1. Smoothing jagged edges without anti-aliasing - Unity3D
  2. How to enable anti-aliasing in A-Frame?

Solution

  • You must enable antialiasing in QGraphicsView:

    class DrawingPanel(QtGui.QGraphicsView):
    
        def __init__(self, parent):
            QtGui.QGraphicsView.__init__(self, parent)
            self.setRenderHint(QtGui.QPainter.Antialiasing)
            [...]