Table of contents
1. The actual combat scene
Practical scenario: Introduction to QPen of PyQt6 in Python
2. Main points of knowledge
Three, rookie combat
QPen
Is a basic graphics object that can draw lines, curves and outlines of shapes such as rectangles, ellipses, polygons, etc.
from PyQt6.QtWidgets import QWidget, QApplication
from PyQt6.QtGui import QPainter, QPen
from PyQt6.QtCore import Qt
import sys
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 280, 270)
self.setWindowTitle('Pen styles')
self.show()
def paintEvent(self, e):
qp = QPainter()
qp.begin(self)
self.drawLines(qp)
qp.end()
def drawLines(self, qp):
pen = QPen(Qt.GlobalColor.black, 2, Qt.PenStyle.SolidLine)
qp.setPen(pen)
qp.drawLine(20, 40, 250, 40)
pen.setStyle(Qt.PenStyle.DashLine)
qp.setPen(pen)
qp.drawLine(20, 80, 250, 80)
pen.setStyle(Qt.PenStyle.DashDotLine)
qp.setPen(pen)
qp.drawLine(20, 120, 250, 120)
pen.setStyle(Qt.PenStyle.DotLine)
qp.setPen(pen)
qp.drawLine(20, 160, 250, 160)
pen.setStyle(Qt.PenStyle.DashDotDotLine)
qp.setPen(pen)
qp.drawLine(20, 200, 250, 200)
pen.setStyle(Qt.PenStyle.CustomDashLine)
pen.setDashPattern([1, 4, 5, 4])
qp.setPen(pen)
qp.drawLine(20, 240, 250, 240)
def main():
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec())
if __name__ == '__main__':
main()
In the example, we have drawn 6 lines. Lines are styled with six different stroke styles. There are five predefined strokes. We can also create custom stroke styles. The last line is styled using a custom stroke style.
pen = QPen(Qt.GlobalColor.black, 2, Qt.PenStyle.SolidLine)
Here an QPen
object is created, the color is black, and the width is 2 pixels, so that the different strokes can be distinguished. Qt.SolidLine
is a predefined stroke.
pen.setStyle(Qt.PenStyle.CustomDashLine) pen.setDashPattern([1, 4, 5, 4]) qp.setPen(pen)
Here we customize a stroke. The style is set to Qt.PenStyle。CustomDashLine
, use the setDashPattern
method to set the specific style, the parameters must be an even number, the odd number defines the dash, and the even number defines the space. The larger the number, the larger the space or dash. The settings here are 1px horizontal line, 4px space, 5px horizontal line, 4px space and so on.
Rookie combat, keep learning!