QtGui.QPen
The QtGui.QPen
is an elementary graphics object. It is used to draw lines, curves and outlines of rectangles, ellipses, polygons, or other shapes.
#!/usr/bin/python # -*- coding: utf-8 -*- """ ZetCode PyQt4 tutorial In this example we draw 6 lines using different pen styles. author: Jan Bodnar website: zetcode.com last edited: September 2011 """ import sys from PyQt4 import QtGui, QtCore class Example(QtGui.QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): self.setGeometry(300, 300, 280, 270) self.setWindowTitle('Pen styles') self.show() def paintEvent(self, e): qp = QtGui.QPainter() qp.begin(self) self.drawLines(qp) qp.end() def drawLines(self, qp): pen = QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine) qp.setPen(pen) qp.drawLine(20, 40, 250, 40) pen.setStyle(QtCore.Qt.DashLine) qp.setPen(pen) qp.drawLine(20, 80, 250, 80) pen.setStyle(QtCore.Qt.DashDotLine) qp.setPen(pen) qp.drawLine(20, 120, 250, 120) pen.setStyle(QtCore.Qt.DotLine) qp.setPen(pen) qp.drawLine(20, 160, 250, 160) pen.setStyle(QtCore.Qt.DashDotDotLine) qp.setPen(pen) qp.drawLine(20, 200, 250, 200) pen.setStyle(QtCore.Qt.CustomDashLine) pen.setDashPattern([1, 4, 5, 4]) qp.setPen(pen) qp.drawLine(20, 240, 250, 240) def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main()
In our example, we draw six lines. The lines are drawn in six different pen styles. There are five predefined pen styles. We can create also custom pen styles. The last line is drawn using a custom pen style.
pen = QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine)
We create a QtGui.QPen
object. The colour is black. The width is set to 2 pixels so that we can see the differences between the pen styles. The QtCore.Qt.SolidLine
is one of the predefined pen styles.
pen.setStyle(QtCore.Qt.CustomDashLine) pen.setDashPattern([1, 4, 5, 4]) qp.setPen(pen)
Here we define a custom pen style. We set a QtCore.Qt.CustomDashLine
pen style and call thesetDashPattern()
method. The list of numbers defines a style. There must be an even number of numbers. Odd numbers define a dash, even numbers space. The greater the number, the greater the space or the dash. Our pattern is 1px dash, 4px space, 5px dash, 4px space etc.
Figure: Pen styles